[英]pack and unpack at the right format in python
我正在寻找从缓冲区解包一个字符串及其长度。
例如,要从此缓冲区获取(4, 'Gégé')
:
b'\\x00\\x04G\\xE9g\\xe9'
有人知道该怎么做吗?
长度数据看起来像一个大端无符号16位整数,字符串数据看起来像是使用Latin1编码。 如果正确的话,您可以像这样提取它:
from struct import unpack
def extract(buff):
return unpack(b'>H', buff[:2])[0], buff[2:].decode('latin1')
buff = b'\x00\x04G\xE9g\xe9'
print(extract(buff))
产量
(4, 'Gégé')
编码的另一种可能性是旧的Windows代码页1252 ,可以使用.decode('cp1252')
对其进行解码。
上面的代码在Python 2和Python 3中都适用。但是在Python 3中,有一个更简单的方法:我们不需要struct.unpack
,我们可以使用int.from_bytes
方法。
def extract(buff):
return int.from_bytes(buff[:2], 'big'), buff[2:].decode('latin1')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.