printing bit representation of numbers in python

Python

Python Problem Overview


I want to print the bit representation of numbers onto console, so that I can see all operations that are being done on bits itself.

How can I possibly do it in python?

Python Solutions


Solution 1 - Python

This kind of thing?

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

Solution 2 - Python

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</sup>

Solution 3 - Python

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}"

Solution 4 - Python

Solution 5 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionvivek kumarView Question on Stackoverflow
Solution 1 - PythonakentView Answer on Stackoverflow
Solution 2 - PythongahooaView Answer on Stackoverflow
Solution 3 - PythonFinlay McWalterView Answer on Stackoverflow
Solution 4 - PythonRoberto BonvalletView Answer on Stackoverflow
Solution 5 - PythonMikhail VView Answer on Stackoverflow