Skip to content

Arduino Bitwise Operators and advanced tricks

The bitwise NOT (~) operand is applied to a single operand.

NOT 0 = 1

NOT 1 = 0

So the not 10101010 becomes 01010101


There are two bit shift operators, the left shift operator << and the right shift operator >>

Generally the left shift operator syntax is :

variable << number_of_bits

and the right shift operator syntax is :

variable >> number_of_bits

The left shift operator shifts the bits to x positions to the left filling the last positions with x zeros .

Example

y = 10101010

x = y << 1  //The resulting x should be  x = 01010100

Another example XXXXXXXX << 5 = XXX00000


 

The right shift operator shifts the bits to x positions to the right filling the first positions with x zeros (most of the times) .

y = 10101010 >> 1 gives 01010101

Another example XXXXXXXX >> 2 = 00XXXXXX

Attention : when you shift x right by y bits (x >> y), and the highest bit in x is a 1, the filled bits depend on the exact data type of x.

If x is of type int, the highest bit is the sign bit, determining whether x is negative or not.

    int x = -16;     // binary: 1111 1111 1111 0000
                     //(the negative sign is the highest bit set to 1)
    int y = x >> 3;  // binary: 1111 1111 1111 1110

This behavior, called sign extension, is often not the behavior we want.
Instead, generally we want zeros to be shifted in from the left. To resolve this problem we just have to typecast the int value into a unsigned int expression :

    int x = -16;                  // binary: 1111 1111 1111 0000
    int y = (unsigned int)x >> 3; // typecast int x into unsigned int.
                                  // binary: 0001 1111 1111 1110

In the next page we will see a real example in order to understand the bitwise operators