printing bit representation of numbers in python

This kind of thing?

>>> ord('a')
97
>>> hex(ord('a'))
'0x61'
>>> bin(ord('a'))
'0b1100001'

In Python 2.6+:

print bin(123)

Results in:

0b1111011

In python 2.x

>>> binary = lambda n: n>0 and [n&1]+binary(n>>1) or []
>>> binary(123)
[1, 1, 0, 1, 1, 1, 1]

Note, example taken from: "Mark Dufour" at http://mail.python.org/pipermail/python-list/2003-December/240914.html


From Python 2.6 - with the string.format method:

"{0:b}".format(0x1234)

in particular, you might like to use padding, so that multiple prints of different numbers still line up:

"{0:16b}".format(0x1234)

and to have left padding with leading 0s rather than spaces:

"{0:016b}".format(0x1234)

From Python 3.6 - with f-strings:

The same three examples, with f-strings, would be:

f"{0x1234:b}"
f"{0x1234:16b}"
f"{0x1234:016b}"

The bin function


Slightly off-topic, but might be helpful. For better user-friendly printing I would use custom print function, define representation characters and group spacing for better readability. Here is an example function, it takes a list/array and the group width:

def bprint(A, grp):
    for x in A:
        brp = "{:08b}".format(x)
        L=[]
        for i,b in enumerate(brp):
            if b=="1":
                L.append("k")
            else: 
                L.append("-")
            if (i+1)%grp ==0 :
                L.append(" ")

        print "".join(L) 

#run
A = [0,1,2,127,128,255]
bprint (A,4)

Output:

---- ----
---- ---k
---- --k-
-kkk kkkk
k--- ----
kkkk kkkk