将十六进制字节的二进制<something>转换为十进制值列表

时间:2019-12-11 01:28:57

标签: python-3.x binary hex

我有以下二进制文件(某物):

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(),因为它变得更复杂了……我那里有一个低字节的4字节整数……最后四个字节是:

b'11 1E 0C 09'

假设是小端,那么上面的十进制是多少?

非常感谢!这实际上是来自CAN总线,我正在将其作为串行端口进行访问(令人沮丧的事情..)

1 个答案:

答案 0 :(得分:1)

假设您有字符串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,)