【问题标题】:How to read UTF16-BE encoded bytes with length header如何读取带有长度标头的 UTF16-BE 编码字节
【发布时间】:2020-01-22 21:09:30
【问题描述】:

我想解码一系列可变长度的字符串,这些字符串已经以 UTF16-BE 编码,前面是一个两字节长的大端整数,表示以下字符串的一半字节长度。例如:

Length    String (encoded)           Length    String (encoded)               ...
\x00\x05  \x00H\x00e\x00l\x00l\x00o  \x00\x06  \x00W\x00o\x00r\x00l\x00d\x00! ...

所有这些字符串及其长度标头都连接在一个大的bytestring 中。

我在内存中将编码的字节串作为bytes 对象。我想要一个可迭代的函数,它会产生字符串,直到它到达ByteString 的末尾。

【问题讨论】:

    标签: python iterable


    【解决方案1】:

    不是很大的改进,但您的代码可以简化一点。

    def decode_strings(byte_string: ByteString) -> Generator[str]:
        with io.BytesIO(byte_string) as stream:
            while (s := stream.read(2)):
                length = int.from_bytes(s, byteorder="big")
                yield bytes.decode(stream.read(length), encoding="utf_16_be")
    

    【讨论】:

    • 谢谢,我感觉新的海象运算符在这里会很实用。
    【解决方案2】:

    目前我是这样做的,但不知何故我在想象 Raymond Hettinger 的 "There must be a better way!"

    import io
    import functools
    from typing import ByteString
    from typing import Iterable
    
    # Decoders
    int_BE = functools.partial(int.from_bytes, byteorder="big")
    utf16_BE = functools.partial(bytes.decode, encoding="utf_16_be")
    
    encoded_strings = b"\x00\x05\x00H\x00e\x00l\x00l\x00o\x00\x06\x00W\x00o\x00r\x00l\x00d\x00!"
    header_length = 2
    
    def decode_strings(byte_string: ByteString) -> Iterable[str]:
        stream = io.BytesIO(byte_string)
        while True:
            length = int_BE(stream.read(header_length))
            if length:
                text = utf16_BE(stream.read(length * 2))
                yield text
            else:
                break
        stream.close()
    
    
    if __name__ == "__main__":
        for text in decode_strings(encoded_strings):
            print(text)
    

    感谢您的任何建议。

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 2011-03-19
      相关资源
      最近更新 更多