2. Bitwise Operators
In the arithmetic-logic unit (which is within the CPU), mathematical operations
like: addition, subtraction, multiplication and division are done in bit-level. To
perform bit-level operations in C programming, bitwise operators are used.
The truth tables for & (Bitwise AND), |(Bitwise OR), and ^(Bitwise XOR)
is as follows −
M N M & N M | N M ^ N
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
3. Bitwise AND
The output of bitwise AND is 1 if the corresponding bits of two
operands is 1. If either bit of an operand is 0, the result of
corresponding bit is evaluated to 0. Bitwise AND operator is
denoted by &.
Let us suppose the bitwise AND operation of two integers 5 and 9.
5 0101
9 1001
5&9 0001 =1 (In decimal)
0 1 0 1
1 0 0 1
0 0 0 1
4. Bitwise OR
The output of bitwise OR is 1 if at least one corresponding bit of
two operands is 1. In C Programming, bitwise OR operator is
denoted by | .
Let us suppose the bitwise OR operation of two integers 5 and 9.
5 0101
9 1001
5|9 1101 =13 (In decimal)
0 1 0 1
1 0 0 1
1 1 1
0
5. Bitwise XOR
The result of bitwise XOR operator is 1 if the corresponding bits of
two operands are opposite. It is denoted by ^.
Let us suppose the bitwise XOR operation of two integers 5 and 9.
5 0101
9 1001
5^9 1100 =12 (In decimal)
0 1 0 1
1 0 0 1
1 1 0 0
6. Bitwise Complement
Bitwise complement operator is a unary operator (works on only one
operand). It changes 1 to 0 and 0 to 1. It is denoted by ~ .
5 0101
~5 1010 =10 (In decimal)
0 1 0 1
1 0 1 0
7. For any integer n bitwise complement of n will be -(n+1) .
The bitwise complement of 5 is 10 (in decimal). The 2's complement
of 10 is -6 . Hence, the output is -6
8. Left Shift Operator
Left shift operator shifts all bits towards left by certain
number of specified bits. It is denoted by <<.
Example 5 << 1
5 = 0101 (In Binary)
5 << 1 = 1010 (Left shift by 1 bits)
(In decimal 10)
0 1 0 1
1 0 1 0
Left shift operator is used to multiply the number by 2n
where n is number of bits
9. Right Shift Operator
Right shift operator shifts all bits towards right by certain
number of specified bits. It is denoted by >>.
Example 5 = 0101 (In Binary)
5 >> 1 = 0010 (Right shift by 1 bits)
(In decimal 2)
0 1 0 1
1 0
0
0
Right shift operator is used to divide the number by 2n
where n is number of bits
10.
11. SUMMARY
Example A=5 B=9
Operators Meaning Example
& Perform bitwise AND operation. (A&B) = 1
i.e. 0001
| Perform bitwise OR operation. (A|B) = 13
i.e. 1101
^ Perform bitwise XOR operation. (A^B) = 12
i.e. 1100
~ Perform bitwise NOT operation. ~A = 10
i.e. 1010
<< Binary Left shift operator shifts all bits towards left by
certain number of specified bits. It is denoted by <<.
A<<1 = 1010
i.e. 10
>> Binary Right shift operator shifts all bits towards right
by certain number of specified bits.
A>>1 = 0010
i.e. 2