如何从 python 中的十六进制字符串中获取最后两个字节
how to get last two bytes from a hex string in python
我有输出 = ( b'\x00\x01\x00\x00\x00\x07\x03\x04\x04\x00\x00\x07\xd0')。
我想得到最后两个字节(07d0)。
之后,我必须将它们转换为十进制。
以下对我有用:
bytes_test = b'\x00\x01\x00\x00\x00\x07\x03\x04\x04\x00\x00\x07\xd0'
print(int.from_bytes(bytes_test[-2:],"big"))
int.from_bytes
可以将任意字节数转换为整数,但是你必须知道你要转换的是小端还是大端:
>>> output = b'\x00\x01\x00\x00\x00\x07\x03\x04\x04\x00\x00\x07\xd0'
>>> output[-2:] # start 2 bytes from the end and grab until end
b'\x07\xd0'
>>> int.from_bytes(output[-2:],'little')
53255
>>> int.from_bytes(output[-2:],'big')
2000
>>> hex(int.from_bytes(output[-2:],'little'))
'0xd007'
>>> hex(int.from_bytes(output[-2:],'big'))
'0x7d0'
我有输出 = ( b'\x00\x01\x00\x00\x00\x07\x03\x04\x04\x00\x00\x07\xd0')。 我想得到最后两个字节(07d0)。 之后,我必须将它们转换为十进制。
以下对我有用:
bytes_test = b'\x00\x01\x00\x00\x00\x07\x03\x04\x04\x00\x00\x07\xd0'
print(int.from_bytes(bytes_test[-2:],"big"))
int.from_bytes
可以将任意字节数转换为整数,但是你必须知道你要转换的是小端还是大端:
>>> output = b'\x00\x01\x00\x00\x00\x07\x03\x04\x04\x00\x00\x07\xd0'
>>> output[-2:] # start 2 bytes from the end and grab until end
b'\x07\xd0'
>>> int.from_bytes(output[-2:],'little')
53255
>>> int.from_bytes(output[-2:],'big')
2000
>>> hex(int.from_bytes(output[-2:],'little'))
'0xd007'
>>> hex(int.from_bytes(output[-2:],'big'))
'0x7d0'