howto print binary number

Joel Bender jjb5 at cornell.edu
Wed May 7 17:03:10 EDT 2008


> 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



More information about the Python-list mailing list