5

我有一个整数,我想将其转换为二进制并将位串存储在从右侧开始的一维数组中。例如,如果输入是,6那么它应该返回一个像[1,1,0]. 如何在python中做到这一点?

4

7 回答 7

6

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.

于 2012-12-01T20:16:42.010 回答
4
>>> 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:

于 2012-12-01T20:16:05.220 回答
3

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 representation
  • bin(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 list
  • map(int, ...) converts the list of strings into a list of integers
于 2012-12-01T20:19:50.990 回答
1

bin如果您的 Python >= 2.6 ,则可以使用该函数:

list(bin(6))[2:]

编辑:哎呀,忘记将项目转换为int

map(int, list(bin(6))[2:])
于 2012-12-01T20:15:10.760 回答
1

在现代 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.

于 2012-12-01T20:15:16.920 回答
1

其他答案bin()用于此。它有效,但我发现使用字符串运算来做数学有点......嗯......蹩脚:

def tobits(x):
    r = []
    while x:
        r.append(x & 1)
        x >>= 1
    return r

tobits(0)返回一个空列表。这可能好或不好,取决于你会用它做什么。因此,如果需要,请将其视为特例。

于 2012-12-01T20:34:08.690 回答
0

您可以使用numpy.unpackbits.

这是带有示例的详细链接:https ://numpy.org/doc/stable/reference/generated/numpy.unpackbits.html

于 2021-06-02T05:27:32.340 回答