Python: Converting String to Binary

A simple code on how to convert string to binary, accessing array string and performing shift operation on binary


#!/usr/bin/python

a_str = ‘10110011’
b_str = “00101010”
a_bin = int(a_str, 2)
b_bin = int(b_str, 2)

print “a “, int(a_bin), a_str
print “b “, int(b_bin), b_str
print “a[0] “, a_str[0]
print “b[0:3]”, b_str[0:3]

#print “c “, c, bin(c)[2:]

print “a << 2 “, a_bin << 2, bin(a_bin << 2)[2:]
print “b >> 2 “, b_bin >> 2, bin(b_bin >> 2)[2:]

The result:

Screen shot 2013-03-08 at 12.37.48 PM

Advertisements