How to do integers to binary lists and back

MRAB python at mrabarnett.plus.com
Thu May 21 18:31:52 EDT 2015


On 2015-05-21 23:20, John Pote wrote:
> Hi everyone.
> I recently had the problem of converting from an integer to its
> representation as a list of binary bits, each bit being an integer 1 or
> 0, and vice versa. E.G.
> 0x53
> becomes
> [ 0, 1, 0, 1, 0, 0, 1, 1 ]
>
> This I wanted to do for integers of many tens, if not hundreds, of bits.
> Python very nicely expands integers to any size required, great feature.
>
> Just wondered if there was a neat way of doing this without resorting to
> a bit bashing loop.
>
> Looking forward to some interesting answers,
> John
>
>
I don't know how efficient you want it to be, but:

 >>> number = 0x53
 >>> bin(number)
'0b1010011'
 >>> bin(number)[2 : ]
'1010011'
 >>> list(map(int, bin(number)[2 : ]))
[1, 0, 1, 0, 0, 1, 1]




More information about the Python-list mailing list