468,737 Members | 1,785 Online

# howto print binary number

hi all,
could you inform how to print binary number?
I.e. something like

print '%b' % my_number

it would be nice would it print exactly 8 binary digits (0-1, with
possible start from 0)

Thank you in advance, D
Jun 27 '08 #1
5 18239
On May 7, 3:13*pm, dmitrey <dmitrey.kros...@scipy.orgwrote:
hi all,
could you inform how to print binary number?
I.e. something like

print '%b' % my_number

it would be nice would it print exactly 8 binary digits (0-1, with
possible start from 0)

Thank you in advance, D
The gmpy works good.
>>import gmpy
print gmpy.digits(66,2).zfill(8)
01000010
Jun 27 '08 #2
dmitrey wrote:
hi all,
could you inform how to print binary number?
I.e. something like

print '%b' % my_number

it would be nice would it print exactly 8 binary digits (0-1, with
possible start from 0)

Thank you in advance, D
--
http://mail.python.org/mailman/listinfo/python-list
Python 3.0 has such a formatting operation, but Python 2.x does not.
However it's not hard to write.

If you really only going to need 8 bits, you can just build a table of
bit patterns for each integer. Try this bit of slight cleverness:
>>b = ['']
for k in range(8):
.... b = [i+j for i in ['0','1'] for j in b]
....
>>len(b)
256
>>b[63]
'00111111'
Gary Herron

Jun 27 '08 #3
Python 3.0 has such a formatting operation, but Python 2.x does not.
However it's not hard to write.
Indeed. Refraining from using named lambdas:
>>def bin(x):
... return ''.join(x & (1 << i) and '1' or '0' for i in
... range(7,-1,-1))
...
>>bin(12)
'00001100'
>>bin(63)
'00111111'

It would be nice to have str(x, 2) like int(x, 2), but there are bigger
fish in pond.
Joel
Jun 27 '08 #4
On Wed, 07 May 2008 13:13:40 -0700, dmitrey wrote:
hi all,
could you inform how to print binary number? I.e. something like

print '%b' % my_number

it would be nice would it print exactly 8 binary digits (0-1, with
possible start from 0)

Thank you in advance, D
Here it is:

def bin(x, digits=0):
oct2bin = ['000','001','010','011','100','101','110','111']
binstring = [oct2bin[int(n)] for n in oct(x)]
return ''.join(binstring).lstrip('0').zfill(digits)
>>bin(5)
'101'
>>bin(0x0FFF, 16)
'0000111111111111'
>>bin(5, 8)
'00000101'

--
Ivan
Jun 27 '08 #5
On May 7, 4:03*pm, Joel Bender <j...@cornell.eduwrote:
Python 3.0 has such a formatting operation, but Python 2.x does not. *
However it's not hard to write.

Indeed. *Refraining from using named lambdas:

* * *>>def bin(x):
* * *... * * return ''.join(x & (1 << i) and '1' or '0' for i in
* * *... * * * * range(7,-1,-1))
* * *...
* * *>>bin(12)
* * *'00001100'
* * *>>bin(63)
* * *'00111111'

It would be nice to have str(x, 2) like int(x, 2), but there are bigger
fish in pond.
+1 str( x, base ) +1
Jun 27 '08 #6

### This discussion thread is closed

Replies have been disabled for this discussion.