Python: Bit Operations

Basic bit operations in Python:


#!/usr/bin/python 

a = 60            # 60 = 0011 1100 
b = 13            # 13 = 0000 1101 
c = 0

print "a = ", (bin(a)[2:]);
print "b = ", (bin(b)[2:]);

c = a & b;        # 12 = 0000 1100
print "a & b = ", (bin(c)[2:]);

c = a | b;        # 61 = 0011 1101 
print "a | b = ", (bin(c)[2:]);

c = a ^ b;        # 49 = 0011 0001
print "a ^ b = ", (bin(c)[2:]);

c = ~a;           # -61 = 1100 0011
print "~a = ", (bin(c)[2:]);

c = a << 2;       # 240 = 1111 0000
print "a <> 2;       # 15 = 0000 1111
print "a >> 2 = ", (bin(c)[2:]);

Result:
Screen shot 2013-03-07 at 3.28.10 PM

An interesting link about bit operation algorithm implementation in Python is here.

Advertisements