tags:

views:

402

answers:

3

Hi

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?

Thanks

+8  A: 

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

gahooa
you can further add bin = lambda b:'0b'+''.join(map(str,binary(b))), so it mimics 2.6+ completely
Anurag Uniyal
A: 

The bin function

Roberto Bonvallet
+1  A: 

This kind of thing?

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