Print bit representation of numbers in python

I want to print a bit representation of numbers on the console so that I can see all the operations performed by the bits themselves.

How can i do this in python?

+46
python
Jun 28 '09 at 2:55
source share
5 answers

This thing?

>>> ord('a') 97 >>> hex(ord('a')) '0x61' >>> bin(ord('a')) '0b1100001' 
+55
Jun 28 '09 at 3:02
source share

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, an example is taken from: "Mark Dufour" at http://mail.python.org/pipermail/python-list/2003-December/240914.html

+23
Jun 28 '09 at 3:00
source share

From Python 2.6 - with the string.format method :

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

in particular, you can use the registration, so that several prints of different numbers still line up:

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

and leave a space with leading 0, not spaces:

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

From Python 3.6 - with f-strings :

The same three examples with f-lines will be:

 f"{0x1234:b}" f"{0x1234:16b}" f"{0x1234:016b}" 
+19
Sep 22 '13 at 16:26
source share
+2
Jun 28 '09 at 3:02
source share

A little off topic, but may be useful. For better convenient printing, I would use a custom print function, define presentation characters and group spacing for better readability. Here is an example function, it takes a list / array and 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 
+1
May 12 '15 at 16:38
source share



All Articles