Python

 

 

 

 

Python - Bitwise Operators

 

NOTE : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x as expected.

 

Operation

Python

Comments

AND

&

Bitwise AND (e.g, x & y)

OR

|

Bitwise AND (e.g, x | y)
NOT

~

Bitwise Complement (e.g, ~x)

XOR

^

Bitwise Exclusive OR (e.g, x ^ y)
SHIFT RIGHT

>>

x >> y
SHIFT LEFT

<<

x << y

 

 

 

Example 01 > Basic Operation

 

This shows some of the examples of how to use these operators. Don't get scared that it might look much more complicated than you think. But the complexity of this example comes from the print out formatting, not from the operator itself. Real operation is highlighted in red. If you are not familiar with format part, refer to Formating a Number section in Number Manipulation page.

 

 

a = 216

b = 133

 

print('a     = ','{0:{1}d}'.format(a,6),'[','{0:0{1}b}'.format(a,16),']')

print('b     = ','{0:{1}d}'.format(b,6),'[','{0:0{1}b}'.format(b,16),']')

print('a & b = ','{0:{1}d}'.format(a & b,6),'[','{0:0{1}b}'.format(a & b,16),']')

print('a | b = ','{0:{1}d}'.format(a | b,6),'[','{0:0{1}b}'.format(a | b,16),']')

print('a ^ b = ','{0:{1}d}'.format(a ^ b,6),'[','{0:0{1}b}'.format(a ^ b,16),']')

print('~a    = ','{0:{1}d}'.format(~a,6),'[','{0:0{1}b}'.format(~a,16),']')

print('~b    = ','{0:{1}d}'.format(~b,6),'[','{0:0{1}b}'.format(~b,16),']')

print('a<<4  = ','{0:{1}d}'.format(a<<4,6),'[','{0:0{1}b}'.format(a<<4,16),']')

print('a>>4  = ','{0:{1}d}'.format(a>>4,6),'[','{0:0{1}b}'.format(a>>4,16),']')

 

 

Result :----------------------------------------------------

 

a     =     216 [ 0000000011011000 ]

b     =     133 [ 0000000010000101 ]

a & b =     128 [ 0000000010000000 ]

a | b =     221 [ 0000000011011101 ]

a ^ b =      93 [ 0000000001011101 ]

~a    =    -217 [ -000000011011001 ]

~b    =    -134 [ -000000010000110 ]

a<<4  =    3456 [ 0000110110000000 ]

a>>4  =      13 [ 0000000000001101 ]