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?
7 Answers
Solution
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.
Getting list of ints from binary representation
EDIT: 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)
Combined solution for edited question
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.
1 Comment
{:b} exists, it's time to get rid of bin(x)[2:] abuse.>>> 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:
You could use this command:
map(int, list(bin(YOUR_NUMBER)[2:]))
What it does is this:
bin(YOUR_NUMBER)convertsYOUR_NUMBERinto its binary representationbin(YOUR_NUMBER)[2:]takes the effective number, because the string is returned in the form'0b110', so you have to remove the0blist(...)converts the string into a listmap(int, ...)converts the list of strings into a list of integers
Comments
You can use the bin function if you have Python >= 2.6:
list(bin(6))[2:]
Edit: oops, forgot to convert items to int:
map(int, list(bin(6))[2:])
Comments
In modern Python you can (>python2.5):
>>> bin(23455)
'0b101101110011111'
Discard the first '0b':
>>> [ bit for bit in bin(23455)[2:] ]
['1', '0', '1', '1', '0', '1', '1', '1', '0', '0', '1', '1', '1', '1', '1']
Everything together:
def get_bits(number):
return [ int(bit) for bit in bin(number)[2:] ]
In 2.5 you will get an NameError: name 'bin' is not defined.
Comments
Others answers use bin() for that. It works, but I find that using string operations to do mathematics is a bit... ehm... lame:
def tobits(x):
r = []
while x:
r.append(x & 1)
x >>= 1
return r
The tobits(0) will return an empty list. That may be nice or not, depending on what you'll do with it. So if needed treat it as a special case.
Comments
You may use numpy.unpackbits.
Here is the detailed link with examples: https://numpy.org/doc/stable/reference/generated/numpy.unpackbits.html