我得到了一个特殊的字符串格式数据包,它具有32个字节的标头,主体包含一个或多个条目之一,每个条目由90个字节组成。
我想使用python处理此字符串。我可以像sock一样读取前32个字节的报头,然后将其从字符串中删除,然后继续读取第一个条目的90个字节吗?
就像是:
str.read(32) # => "x01x02..."
str.read(90) # => "x02x05..."
您可以使用StringIO读取类似文件的字符串
>>> import StringIO
>>> s = 'Hello, World!'
>>> sio = StringIO.StringIO(s)
>>> sio.read(6)
'Hello,'
>>> sio.read()
' World!'
我还建议您看看struct模块,以获取有关解析二进制数据的帮助
>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
您使用格式字符串定义数据的格式,因此'hhl'
在上面的示例中为short (2 bytes), short (2 bytes), int (4 bytes)
。它还支持在格式字符串中指定字节序(字节顺序)。
例如,如果标题格式为uint, 4 byte str, uint, uint, ushort, ulong
:
>>> import struct
>>> data = ''.join(chr(i) for i in range(128)) * 10
>>> hdr_fmt = 'I4sIIHL'
>>> struct.calcsize(hdr_fmt)
32
>>> struct.unpack_from(hdr_fmt, data, 0)
(50462976, '\x04\x05\x06\x07', 185207048, 252579084, 4368, 2242261671028070680)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句