从Python中读取字符串中的字节

时间:2022-06-04 22:37:06

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.

我有一个python字符串表示从网络读取的字节,我需要从该字符串连续读取几个字节。例如,我在一个字符串中有9个字节,我需要读取4个字节作为整数,2个字节作为短,3个字节的自定义数据类型。

Is there a reader in python to do something like:

python中是否有读者可以执行以下操作:

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.

我以为使用struct.unpack,但我不知道如何处理非原始类型。

Any idea ?

任何的想法 ?

Thanks.

1 个解决方案

#1


2  

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

#1


2  

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