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]

11
  • 1
    I tried this: binary = 0 while num != 0: bit = num % 2 binary = bit +(10* binary) num = num / 2 binary=[binary] return binary but it doesn't give me commas between the numbers, and it doesn't always add the zeros. Commented Nov 26, 2012 at 2:39
  • What have you tried? You might want to look at the python docs for the function bin. Commented Nov 26, 2012 at 2:39
  • I want to do it without that function if I can Commented Nov 26, 2012 at 2:39
  • 3
    This question has already been asked. Commented Nov 26, 2012 at 2:40
  • 1
    @johnthexiii -- See this post on meta Commented Nov 26, 2012 at 3:02

3 Answers 3

32

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

Sign up to request clarification or add additional context in comments.

1 Comment

Relying on string representation details and going from an integer to a string and then to a list seems....suboptimal.
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

Comments

7

In the spirit of your original attempt:

binary = []
while num != 0:
    bit = num % 2
    binary.insert(0, bit)
    num = num / 2

1 Comment

Would be better to .append() the bits then .reverse() the list at the end rather than inserting at the start of the list.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.