28

Possible Duplicate:
Convert an integer to binary without using the built-in bin function

how do I convert a decimal number into a binary list.

For example, how do I change 8 into [1,0,0,0]

Community
  • 1
  • 1
booboboobobob
  • 295
  • 1
  • 3
  • 4

3 Answers3

31

You can probably use the builtin bin function:

bin(8) #'0b1000'

to get the list:

[int(x) for x in bin(8)[2:]]

Although it seems like there's probably a better way...

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 4
    Relying on string representation details and going from an integer to a string and then to a list seems....suboptimal. – slacy Feb 10 '17 at 23:56
22

Try this:

>>> list('{0:0b}'.format(8))
['1', '0', '0', '0']

Edit -- Ooops, you wanted integers:

>>> [int(x) for x in list('{0:0b}'.format(8))]
[1, 0, 0, 0]

Another edit --

mgilson's version is a little bit faster:

$ python -m timeit "[int(x) for x in list('{0:0b}'.format(8))]"
100000 loops, best of 3: 5.37 usec per loop
$ python -m timeit "[int(x) for x in bin(8)[2:]]"
100000 loops, best of 3: 4.26 usec per loop
Sean Redmond
  • 3,974
  • 22
  • 28
7

In the spirit of your original attempt:

binary = []
while num != 0:
    bit = num % 2
    binary.insert(0, bit)
    num = num / 2
Alexey Feldgendler
  • 1,792
  • 9
  • 17
  • 4
    Would be better to `.append()` the bits then `.reverse()` the list at the end rather than `insert`ing at the start of the list. – Tim Nov 26 '12 at 02:58