繁体   English   中英

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

[英]Read bytes from string in Python

我有一个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,但我不知道如何处理非原始类型。

任何的想法 ?

谢谢。

我想你想要这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM