howto print binary number
Gary Herron
gherron at islandtraining.com
Wed May 7 16:44:46 EDT 2008
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
More information about the Python-list
mailing list