1

I got a special packet in string format, which has 32 bytes header and the body contains one of more entries, each consist of 90 bytes.

I want to process this string using python. Can I just read like sock read first 32 bytes header, and take it off the string, and continue read 90 bytes of the first entry?

something like:

str.read(32) # => "x01x02..."
str.read(90) # => "x02x05..."
3
  • slicing ( s[5:] ) doesn't help? May 16, 2014 at 6:09
  • Are you using python 2.x or 3.x ?
    – Roberto
    May 16, 2014 at 6:12
  • @Roberto I'm using python 2.x
    – mko
    May 16, 2014 at 6:12

3 Answers 3

7

You can use StringIO to read a string like a file

>>> import StringIO
>>> s = 'Hello, World!'
>>> sio = StringIO.StringIO(s)
>>> sio.read(6)
'Hello,'
>>> sio.read()
' World!'

I would also suggest you take a look at the struct module for help with parsing binary data

>>> 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)

You define the format of the data using format strings, so 'hhl' in the above example is short (2 bytes), short (2 bytes), int (4 bytes). It also supports specifying endianness (byte order) in the format string.

For example if your header format was 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)
5

To split the packet into a 32 byte header and body:

header = packet[:32]
body = packet[32:]

To further split the body into one or more entries:

entries = [packet[i:i+90] for i in range(0, len(packet), 90)]
4

In python 2.x you could do simply:

header = s[:32]
body = s[32:32+90]

In python 3.x all strings are unicode, so I would convert to bytearray firstly:

s = bytearray(s)
header = s[:32]
body = s[32:32+90]

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.