### Bitwise Operators

In C, byte is the lowest level where we can perform an operation. Applying these Bitwise operators on bytes helps us perform bit level operation. When you combine these operators with any two bytes, it results in another byte (8-bits).

Suppose we have two numbers 3 and 6. With basic arithmetic knowledge, we say 3 + 6 =9. Here 3 and 6 are the **Operands**, "+" is the **Operator** and 9 is the result. Keeping this in mind, we will apply the same logic on a set of binary digits. Consider two variables “a” and “b”.

a = 01101111 = 0x6f

b = 10011001 = 0x99

Bitwise Operators available in C are: **AND** (&), **OR** (|), **XOR** (^) and **NOT** (~). There are also bit shift operators viz. **Bit left shift** (<<) and **Bit right shift **(>>) operators. We will apply these operators on bits and see the result in a **truth table.**

**& : Bitwise "AND" Operator. **

**Truth Table**

1 & 1 = 1

1 & 0 = 0

0 & 1 = 0

0 & 0 = 0

The result is 1 if both the operands are 1, else 0.

a & b = 01101111 & 10011001 = 00001001 = 0x09

**| : Bitwise "OR" Operator**

1 | 1 = 1

1 | 0 = 1

0 | 1 = 1

0 | 0 = 0

Here, the result is 1 if any of the operands are 1, else 0.

a | b = 01101111 | 10011001 = 11111111 = 0xff

**^ : Bitwise "XOR" Operator**

1 ^ 1 = 0

1 ^ 0 = 1

0 ^ 1 = 1

0 ^ 0 = 0

For XOR Operator between two operands, the result is 1 if and only if one of the operand is 1, not both.

a ^ b = 01101111 ^ 10011001 = 11110110 = 0xf6

**~ : Bitwise "NOT" Operator (A.K.A Bitwise Ones Complement)**

~1 = 0

~0 = 1

This operator does nothing more than flipping a bit from 1 to 0 and 0 to 1.

~a = ~(01101111) = 10010000 = 0x90

~b = ~(10011001) = 01100110 = 0x66

Next we will look at Bit shift / Binary shift Operators. Binary shift operators are used to shift bits to left or right as specified in the right operand.

**<< Binary Left Shift Operator**

This shifts left operand value to left by number of bits specified in the right operand. In other words, Binary left shift moves bits to a specified number of places to the left. The least significant bit is appended with 0 and most significant bit is dropped.

If a = 01101111

a << 3 = 01111000

If b = 10011001

b << 3 = 11001000

**>> Binary Right Shift Operator**

This shifts left operand value to right by number of bits specified by the right operand. The most significant bit is appended with 0 and least significant bit is dropped.

If a = 01101111

a >> 2 = 00011011

If b = 10011001

b >> 5 = 00000100

If you are well acquainted with Bitwise Operators and Bit shift Operators, we will move on to Assignment Operators.

#### Tutorial index:

Do you have anything to say?

Visit the Forum to discuss, learn and share anything related to robotics and electronics !!