howto print binary number

Ivan Illarionov ivan.illarionov at gmail.com
Wed May 7 17:46:38 EDT 2008


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



More information about the Python-list mailing list