将十六进制字节的二进制 <something> 转换为十进制值列表
Convert binary <something> of hex bytes to list of decimal values
我有以下二进制(东西):
test = b'40000000111E0C09'
每两位是我要出来的十六进制数,所以下面比上面更清楚:
test = b'40 00 00 00 11 1E 0C 09'
0x40 = 64 in decimal
0x00 = 0 in decimal
0x11 = 17 in decimal
0x1E = 30 in decimal
你懂的。
如何使用 struct.unpack(fmt, binary)
来获取值?我问 struct.unpack()
因为它变得更复杂......我在那里有一个 little-endian 4 字节整数......最后四个字节是:
b'11 1E 0C 09'
假设它是小端字节序,上面的十进制数是多少?
非常感谢!这实际上来自 CAN 总线,我正在将其作为串行端口访问(令人沮丧的东西..)
假设您有字符串 b'40000000111E0C09'
,您可以使用带有十六进制参数的 codecs.decode()
将其解码为字节形式:
import struct
from codecs import decode
test = b'40000000111E0C09'
test_decoded = decode(test, 'hex') # from hex string to bytes
for i in test_decoded:
print('{:#04x} {}'.format(i, i))
打印:
0x40 64
0x00 0
0x00 0
0x00 0
0x11 17
0x1e 30
0x0c 12
0x09 9
要将最后四个字节作为 UINT32(小端),您可以这样做 (struct
docs)
print( struct.unpack('<I', test_decoded[-4:]) )
打印:
(151789073,)
我有以下二进制(东西):
test = b'40000000111E0C09'
每两位是我要出来的十六进制数,所以下面比上面更清楚:
test = b'40 00 00 00 11 1E 0C 09'
0x40 = 64 in decimal
0x00 = 0 in decimal
0x11 = 17 in decimal
0x1E = 30 in decimal
你懂的。
如何使用 struct.unpack(fmt, binary)
来获取值?我问 struct.unpack()
因为它变得更复杂......我在那里有一个 little-endian 4 字节整数......最后四个字节是:
b'11 1E 0C 09'
假设它是小端字节序,上面的十进制数是多少?
非常感谢!这实际上来自 CAN 总线,我正在将其作为串行端口访问(令人沮丧的东西..)
假设您有字符串 b'40000000111E0C09'
,您可以使用带有十六进制参数的 codecs.decode()
将其解码为字节形式:
import struct
from codecs import decode
test = b'40000000111E0C09'
test_decoded = decode(test, 'hex') # from hex string to bytes
for i in test_decoded:
print('{:#04x} {}'.format(i, i))
打印:
0x40 64
0x00 0
0x00 0
0x00 0
0x11 17
0x1e 30
0x0c 12
0x09 9
要将最后四个字节作为 UINT32(小端),您可以这样做 (struct
docs)
print( struct.unpack('<I', test_decoded[-4:]) )
打印:
(151789073,)