Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert decimal to binary list in python [duplicate]

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]

like image 378
booboboobobob Avatar asked Nov 26 '12 02:11

booboboobobob


People also ask

How do you convert a decimal to a binary list in Python?

Using bin. The bin() is a in-built function which can also be used in a similar way as above. This function Python bin() function converts an integer number to a binary string prefixed with 0b.

How do you convert a repeating decimal to binary?

A common algorithm for converting a decimal number that is between 0 and 1 to binary is to multiply by 2 and record the integer part of the result. Then, you subtract that integer from the result and repeat the process.

What is bin function in Python?

The bin() function returns the binary version of a specified integer. The result will always start with the prefix 0b .


1 Answers

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

like image 104
mgilson Avatar answered Oct 10 '22 23:10

mgilson