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]
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]
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...
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
In the spirit of your original attempt:
binary = []
while num != 0:
bit = num % 2
binary.insert(0, bit)
num = num / 2