Bitwise operator



Bitwise Operator
Sign
Bitwise AND
&
Bitwise OR
|
Bitwise XOR
^
Bitwise Complement
~
Bitwise Left
<< 
Shift Bitwise Right
>> 










Truth Table for & , | , ^



a
b
a &b
a |b
a ^b
0
0
0
0
0
0
1
0
1
1
1
1
1
1
0
1
0
0
1
1



Operation on AND (a & b)

If a = 20, b = 12, then

Decimal Value
Binary Value

20
00010100

12
00001100
4
     00000100



Operation on OR (a | b)

If a = 20, b = 12, then


Decimal Value
Binary Value

20
00010100

12
00001100
28
     00011100


Operation on XOR (a ^ b)

If a = 20, b = 12, then


Decimal Value
Binary Value

20
00010100

12
00001100
24
        00011000



Binary Left Shift (<<) and Right Shift (>>)

Left Shift (<<)


Example:- a = 20; / * 0001 0100 * /
a << Shifts every binary number in binary value of numeric value in 2 with 2 binary numbers left side.
Example:-a = 20; / * 0001 0100 * / So its 0101 0000 means 80.


Right Shift (>>) 

Example :- a = 20; / * 0001 0100 * / 
This is completely opposite from Left shift.
Right Shift a >> Shifts every binary number in binary value of numeric value in 2 to 2 binary numbers from right side. 
Example:- a = 20; / * 0001 0100 * / So its 0000 0101 means 5.



Complement Operator (~)

  • This operator does all the bit reverse.
  • This operator reduces 0 to 1 and 0 to 0.

Decimal Value
Binary Value

~12

00001100

243
11110011


Why did 243 come here instead of Output -13?
2's Complement of 243 - (reverse of 243 in binary + 1)


Operation on 2's Complement (~)

Decimal Value

Binary value
2’s Complement
243
11110011
(00001100+1) = - (00001101)
= -13 (Output)







Bitwise Operator



For Example:-

Source Code:

x= 20 # 0001 0100
y = 12 # 0000 1100

z = x & y
print ("value of z is", z) # 4 = 0000 0100

z = x | y
print ("value of z is", z) # 28 = 0001 1100

z = x ^ y
print ("value of z is", z) # 24 = 0001 1000

print ("value of y is", ~ y) # -13 = 1111 0011

z = x << 2
print ("value of z is", z) # 80 = 0101 0000

z = x >> 2
print ("value of z is", z) # 5 = 0000 0101



Output

value of c is 4
value of c is 28
value of c is 24
value of c is -13
value of c is 80
value of b is 5