Python 将字节转换为位?
我使用的是Python3.6,我需要将一个整数转换为单个位的列表。例如,如果我有:Python 将字节转换为位?,python,python-3.x,Python,Python 3.x,我使用的是Python3.6,我需要将一个整数转换为单个位的列表。例如,如果我有: def bitstring_to_bytes(s): return int(s, 8).to_bytes(8, byteorder='big') command_binary = format(1, '08b') bin_to_byte = bitstring_to_bytes(command_binary) 当前输出b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01
def bitstring_to_bytes(s):
return int(s, 8).to_bytes(8, byteorder='big')
command_binary = format(1, '08b')
bin_to_byte = bitstring_to_bytes(command_binary)
当前输出b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01'
但我需要一个整数列表(但采用十六进制格式),如so[0x00,0x00…0x01]
,以便将其传递给另一个函数。我被这部分卡住了。一个衬里:
list(map(lambda b: bin(int(b)), list(str(bin( <your integer> ))[2:])))
list(map(lambda b:bin(int(b)),list(str(bin())[2:]))
或
list(map(lambda b:hex(int(b)),list(str(bin())[2:]))
它很难看,但我敢肯定它确实能满足您的需要。使用cast-into
bytes
类型进行简单的列表理解怎么样
bin_to_byte = b'\x00\x00\x00\x00\x00\x00\x00\x01'
list_of_bytes = [bytes([i]) for i in bin_to_byte]
print(list_of_bytes)
# [b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x00', b'\x01']
它的作用几乎与列表(bin\u to\u byte)
相同,希望它将强制保持字节而不是int
。如果您确实需要一个int
列表,那么是的,list(bin到字节)
就足够了
如您所见,列表中的每一项都不是int
或str
,而是bytes
:
>>> isinstance(list_of_bytes[0], str)
False
>>> isinstance(list_of_bytes[0], int)
False
>>> isinstance(list_of_bytes[0], bytes)
True
因为使用时的问题是它会将项目转换为字符串,即使它们是十六进制形式,例如
bin_to_byte = b'\x00\x00\x00\x00\x00\x00\x00\x01'
list_of_hex = list(map(hex, (bin_to_byte)))
print(list_of_hex)
# ['0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x1']
print(isinstance(list_of_hex[0], str))
# True
list(bin-to-byte)
会给你一个整数列表,这就是你想要的吗?您将看不到[0x00,…]
,因为这不是整数在输出中的表示方式,尽管这是一种有效的文字形式。您可以尝试映射(int,bin(str(num))[2:])
@jonrsharpe它必须是那种形式,因为我将通过SPI连接发送数据。它看起来很接近,没有格式化列表(map(十六进制,元组))
-->
['0x0','0x0',…,'0x1']@dbosk您需要正确指定所需内容。照此,您提供的示例输出与列表(b'\x00\x00\x00\x00\x00\x00\x00\x01'的结果完全相同)
。如果这不是你想要的,那么你需要告诉我们确切的是什么。OP有一个int
s的列表作为他们想要的输出。这些方法提供str
的列表。我认为OP对他们的要求是模糊的。它可以工作,它给我一个字符串列表。有没有办法让它保持十六进制mat?我会编辑这个问题不确定,我必须坐下来测试一下。我知道当你在python中使用十六进制或二进制时,例如0x1或0b1,它会将其读取为一个int。但是如果你丢失了十六进制格式。所以如果你使用[0x1,0xff,0x3],python会将其作为[1,255,3]接受
bin_to_byte = b'\x00\x00\x00\x00\x00\x00\x00\x01'
list_of_hex = list(map(hex, (bin_to_byte)))
print(list_of_hex)
# ['0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x1']
print(isinstance(list_of_hex[0], str))
# True