从字符串中读取字节(Python)

3 投票
1 回答
2205 浏览
提问于 2025-04-17 23:08

我有一个用Python表示的字符串,这个字符串是从网络上读取的字节数据。我需要从这个字符串中依次读取几个字节。比如说,我的字符串里有9个字节,我需要把其中的4个字节当作整数读取,2个字节当作短整数读取,还有3个字节是自定义的数据类型。

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

我想用struct.unpack这个方法,但我不知道怎么处理那些不是基本类型的数据。

有什么好的建议吗?

谢谢。

1 个回答

2

我猜你想要的是这个:

import struct
integer, short = struct.unpack('>ih', my_string)
custom = customType.Unpack(my_string[6:9])

或者也许是这个:

from StringIO import StringIO
reader = StringIO(my_string)
integer, short = struct.unpack('>ih', reader.read(6))
custom = customType.Unpack(reader.read(3))

撰写回答