Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing bit representation of numbers in python

Tags:

python

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?

like image 252
vivek kumar Avatar asked Jun 28 '09 02:06

vivek kumar


People also ask

How many bits are numbers in Python?

To be safe, Python allocates a fixed number of bytes of space in memory for each variable of a normal integer type, which is known as int in Python. Typically, an integer occupies four bytes, or 32 bits.


2 Answers

This kind of thing?

>>> ord('a') 97 >>> hex(ord('a')) '0x61' >>> bin(ord('a')) '0b1100001' 
like image 142
akent Avatar answered Sep 21 '22 23:09

akent


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

like image 29
gahooa Avatar answered Sep 21 '22 23:09

gahooa