Bitwise Operators

Operators that performs on bits (0 or 1) are known as bitwise operators. There are six bitwise operators

& AND
| OR
^ XOR
~ NOT
>> Right Shift
<< Left Shift






Behavior of operators
Nature of operators

Bitwise AND (&)
0&0 is 0
0&1 is 0
1&0 is 0
1&1 is 1

Bitwise OR ( | )
0|0 is 0
0|1 is 1
1|0 is 1
1|1 is 1

Bitwise XOR (^)
0^0 is 0
0^1 is 1
1^0 is 1
1^1 is 0
Bitwise NOT (~)
~0 is 1
~1 is 0

Example
int main()
{
int x;
x=5&12;
printf(“%d”,x);
return(0);
}

Output is:
4

Explanation:

Bitwise AND applies on 5 and 12. We need to convert them in binary.
5 =00000000 00000000 00000000 00000101
12 =00000000 00000000 00000000 00001100
& ————————————
4=00000000 00000000 00000000 00000100

Shift Operators
Right shift >>
Left shift << int main()
{
int x;
x=12>>2;
printf(“%d”,x);
return(0);
}

Output:
3

Explanation:

Convert 12 into binary and shift bits to their right 2 times. This makes last two bits out and two new bits (always 0) append at the left.

12=00000000 00000000 00000000 00001100
Right shift two times
3 =00000000 00000000 00000000 00000011

main()
{
int x;
x=12<<2; printf(“%d”,x); return(0); }

Output :
48

Explanation:

Convert 12 into binary and shift bits to their left 2 times. This makes last two left most bits out and two new bits (always 0) append at the right.

12=00000000 00000000 00000000 00001100
Left shift two times
48=00000000 00000000 00000000 00110000

Bitwise operators
Tagged on: