I have an integer which I want to convert to binary and store the string of bits in an one-dimensional array starting from the right. For example, if the input is 6
then it should return an array like [1,1,0]
. How to do it in python?
Probably the easiest way is not to use bin()
and string slicing, but use features of .format()
:
'{:b}'.format(some_int)
How it behaves:
>>> print '{:b}'.format(6)
110
>>> print '{:b}'.format(123)
1111011
In case of bin()
you just get the same string, but prepended with "0b
", so you have to remove it.
int
s from binary representationEDIT: Ok, so do not want just a string, but rather a list of integers. You can do it like that:
your_list = map(int, your_string)
So the whole process would look like this:
your_list = map(int, '{:b}'.format(your_int))
A lot cleaner than using bin()
in my opinion.
You could use this command:
map(int, list(bin(YOUR_NUMBER)[2:]))
What it does is this:
bin(YOUR_NUMBER)
converts YOUR_NUMBER
into its binary representationbin(YOUR_NUMBER)[2:]
takes the effective number, because the string is returned in the form '0b110'
, so you have to remove the 0b
list(...)
converts the string into a listmap(int, ...)
converts the list of strings into a list of integers>>> map(int, bin(6)[2:])
[1, 1, 0]
If you don't want a list of ints (but instead one of strings) you can omit the map
component and instead do:
>>> list(bin(6)[2:])
['1', '1', '0']
Relevant documentation:
bin
list
map
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