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]
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.
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.
The bin() function returns the binary version of a specified integer. The result will always start with the prefix 0b .
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With