如何在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]
问题答案:
input = 0x15
output = [int(x) for x in '{:08b}'.format(input)]
{0:0=8b}'.format(0x15)
用8位数字表示您input
的binary
格式0 padding
,然后使用列表推导创建位列表。
另外,您可以使用map
功能:
output = map(int, [x for x in '{:08b}'.format(0x15)])
编辑:可变位宽
如果要使位数可变,这是一种方法:
width = 8 #8bit width
output = [int(x) for x in '{:0{size}b}'.format(0x15,size=width)]
output = map(int, [x for x in '{:0{size}b}'.format(0x15,size=width)])
这已在Python 2.7中进行了测试