[英]how to get last two bytes from a hex string in python
我有 output = ( b'\x00\x01\x00\x00\x00\x07\x03\x04\x04\x00\x00\x07\xd0')。 我想得到最后两个字节(07d0)。 之后,我必须将它们转换为十进制。
int.from_bytes
可以将任意数量的字节转换为 integer,但您必须知道要转换 little-endian 还是 big-endian:
>>> 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'
以下对我有用:
bytes_test = b'\x00\x01\x00\x00\x00\x07\x03\x04\x04\x00\x00\x07\xd0'
print(int.from_bytes(bytes_test[-2:],"big"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.