I have a python string representing bytes read from network, I need to read successively several bytes from this string. For example I have 9 bytes in a string, I need to read 4 bytes as integer, 2 bytes as short, and 3 bytes of custom data type.
Is there a reader in python to do something like:
reader = reader(my_string)
integer = int.from_bytes(reader.read(4), 'big')
short = int.from_bytes(reader.read(2), 'big')
custom = customType.Unpack(reader.read(3))
I thought use struct.unpack, but I don't know how to handle non-primitive types.
Any idea ?
Thanks.
-
1Well, what is your custom, non-primitive type, exactly?John Zwinck– John Zwinck2014年03月20日 14:18:47 +00:00Commented Mar 20, 2014 at 14:18
-
It's a representation of another datas, as primitive types, and only this custom type know how to unpack it. Maybe that in my example, the custom type is 1 byte and 1 short.user3442365– user34423652014年03月20日 14:20:22 +00:00Commented Mar 20, 2014 at 14:20
-
3I don't understand. You're saying you have the code which knows how to unpack it, and you want us to tell you how to unpack it, without the code you have to unpack it?John Zwinck– John Zwinck2014年03月20日 14:21:55 +00:00Commented Mar 20, 2014 at 14:21
-
1The struct module is tailor made for this.Antimony– Antimony2014年03月20日 14:22:21 +00:00Commented Mar 20, 2014 at 14:22
-
What I want is to extract datas from string representing bytes. I have the code to unpack everything but I need a reader to read N bytes for each types. If I send the reader to my custom class I want it to be able to read from the current position in the string. For example : I read 4 bytes, and give the reader to another class wich will read N bytes, and then give it to another class wich will read X more bytes etc ...user3442365– user34423652014年03月20日 14:25:19 +00:00Commented Mar 20, 2014 at 14:25
1 Answer 1
I suppose you want this:
import struct
integer, short = struct.unpack('>ih', my_string)
custom = customType.Unpack(my_string[6:9])
Or maybe this:
from StringIO import StringIO
reader = StringIO(my_string)
integer, short = struct.unpack('>ih', reader.read(6))
custom = customType.Unpack(reader.read(3))
answered Mar 20, 2014 at 14:24
John Zwinck
252k44 gold badges347 silver badges459 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
stanleyxu2005
Read the section struct and then
import structlang-py