我有一个整数,我想将其转换为二进制并将位串存储在从右侧开始的一维数组中。例如,如果输入是,6
那么它应该返回一个像[1,1,0]
. 如何在python中做到这一点?
7 回答
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 int
s 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.
You could use this command:
map(int, list(bin(YOUR_NUMBER)[2:]))
What it does is this:
bin(YOUR_NUMBER)
convertsYOUR_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 the0b
list(...)
converts the string into a listmap(int, ...)
converts the list of strings into a list of integers
在现代 Python 中,您可以(>python2.5
):
>>> bin(23455)
'0b101101110011111'
丢弃第一个'0b':
>>> [ bit for bit in bin(23455)[2:] ]
['1', '0', '1', '1', '0', '1', '1', '1', '0', '0', '1', '1', '1', '1', '1']
一切都在一起:
def get_bits(number):
return [ int(bit) for bit in bin(number)[2:] ]
在 2.5 中,您将获得一个NameError: name 'bin' is not defined
.
其他答案bin()
用于此。它有效,但我发现使用字符串运算来做数学有点......嗯......蹩脚:
def tobits(x):
r = []
while x:
r.append(x & 1)
x >>= 1
return r
将tobits(0)
返回一个空列表。这可能好或不好,取决于你会用它做什么。因此,如果需要,请将其视为特例。
您可以使用numpy.unpackbits
.
这是带有示例的详细链接:https ://numpy.org/doc/stable/reference/generated/numpy.unpackbits.html