How to do integers to binary lists and back

Ben Finney ben+python at benfinney.id.au
Thu May 21 18:31:12 EDT 2015


John Pote <johnhpote at o2.co.uk> writes:

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

Is this a homework assignment?

> E.G.
> 0x53
> becomes
> [ 0, 1, 0, 1, 0, 0, 1, 1 ]

>>> foo = 4567

>>> foo
4567
>>> "{foo:d}".format(foo=foo)
'4567'
>>> "{foo:b}".format(foo=foo)
'1000111010111'

>>> foo_binary_text = "{foo:b}".format(foo=foo)
>>> foo_binary_digits = list(foo_binary_text)
>>> foo_binary_digits
['1', '0', '0', '0', '1', '1', '1', '0', '1', '0', '1', '1', '1']

> Just wondered if there was a neat way of doing this without resorting
> to a bit bashing loop.

Python's string formatting and sequence types are quite powerful.

-- 
 \       “As far as the laws of mathematics refer to reality, they are |
  `\    not certain, and as far as they are certain, they do not refer |
_o__)                              to reality.” —Albert Einstein, 1983 |
Ben Finney




More information about the Python-list mailing list