如何将整数转换为Python中的位列表

Sub*_*due 7 python string list

我想知道是否有比现有方法更好的方法.

我试图将一个整数表示为一个位列表,只有当整数<128时才将其填充为8位:

Example input: 0x15
Desired output: [0, 0, 0, 1, 0, 1, 0, 1]
Run Code Online (Sandbox Code Playgroud)

我是通过以下方式完成的:

input = 0x15
output = deque([int(i) for i in list(bin(input))[2:]])
while len(output) != 8:
    output.appendleft(0)
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法在python中执行此操作?

编辑: 我想将任何整数转换为二进制列表.仅当数字需要少于8位来表示时才填充到8.

Another Example input: 0x715
Desired output: [1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1]
Run Code Online (Sandbox Code Playgroud)

Iro*_*ist 8

number = 0x15

output = [int(x) for x in '{:08b}'.format(number)]
Run Code Online (Sandbox Code Playgroud)

'{:08b}'.format(number)表示您的numberinbinary格式,用 0 填充到 8 位数字,然后使用列表理解来创建位列表。

或者,您可以使用map函数:

output = map(int, '{:08b}'.format(0x15))
Run Code Online (Sandbox Code Playgroud)

如果您想使用可变位数,这里有一种方法:

width = 8  # 8bit width
output = [int(x) for x in '{:0{size}b}'.format(0x15, size=width)]
output = map(int, '{:0{size}b}'.format(0x15, size=width))
Run Code Online (Sandbox Code Playgroud)

对于 Python 3map(...)list()(map在 Python 2 中返回一个列表,但在 3 中返回一个迭代器) 包装调用。


Amb*_*ber 5

对于固定大小的8位:

num = 0x15
out = [1 if num & (1 << (7-n)) else 0 for n in range(8)]
Run Code Online (Sandbox Code Playgroud)

(1 << (7-n))创建一个给定的位置上的单位掩码,然后按位&测试,看看是否位在数设置.具有n到0至7的结果在所有的字节8位的工作,以进行测试.

对于任意大小的数字:

import math
num = 0x715
bits = int(max(8, math.log(num, 2)+1))
out = [1 if num & (1 << (bits-1-n)) else 0 for n in range(bits)]
Run Code Online (Sandbox Code Playgroud)


Yu *_*Hao 5

>>> [int(n) for n in bin(0x15)[2:].zfill(8)]
[0, 0, 0, 1, 0, 1, 0, 1]
Run Code Online (Sandbox Code Playgroud)

切片[2:]是删除0b前缀,zfill(8)是在左边填充零.


You*_*ode 5

解决方案

适用于任意位数,比接受的答案当前投票最高的答案更快:

num = 0xAAAA
bit_list = [(num >> shift_ind) & 1
             for shift_ind in range(num.bit_length())] # little endian
bit_list.reverse() # big endian
Run Code Online (Sandbox Code Playgroud)
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]
Run Code Online (Sandbox Code Playgroud)

时间安排

from timeit import timeit

def accepted_answer(number):
    output = [int(x) for x in '{:08b}'.format(number)]

    return output

def highest_voted_answer(num):
    out = [1 if num & (1 << (7-n)) else 0 for n in range(8)]

    return out

def this_answer(num):
    bit_list = [(num >> shift_ind) & 1
                for shift_ind in range(num.bit_length())] # little endian
    bit_list.reverse() # big endian

    return bit_list

NUM = 0x15
ITERATIONS = int(1e7)

print(timeit(lambda: accepted_answer(NUM), number=ITERATIONS))
print(timeit(lambda: highest_voted_answer(NUM), number=ITERATIONS))
print(timeit(lambda: this_answer(NUM), number=ITERATIONS))
Run Code Online (Sandbox Code Playgroud)
9.884788331000891
9.262861715000327
6.484631327999523
Run Code Online (Sandbox Code Playgroud)