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

2024-04-28 11:30:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道有没有比我现在的方法更好的方法。

我试图将一个整数表示为一个位列表,只有当整数是<;128时,才将其左移到8位

Example input: 0x15
Desired output: [0, 0, 0, 1, 0, 1, 0, 1]

我是这样做的:

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

在python中有更好的方法吗?

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

Another Example input: 0x715
Desired output: [1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1]

Tags: 方法inlt列表forinputoutputbin