howto print binary number

D

dmitrey

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
 
M

Mensanator

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.
01000010
 
G

Gary Herron

dmitrey said:
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
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]
....
'00111111'


Gary Herron
 
J

Joel Bender

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:
... return ''.join(x & (1 << i) and '1' or '0' for i in
... range(7,-1,-1))
... '00111111'

It would be nice to have str(x, 2) like int(x, 2), but there are bigger
fish in pond.


Joel
 
I

Ivan Illarionov

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)
'00000101'
 
C

castironpi

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top