How can you decode a UTF-8 character split across input chunks?

An incremental decoder buffers bytes that do not yet form a complete character and resumes on the next chunk.

Python example and interpretation

The three UTF-8 bytes of 数 straddle two chunks. Mark the last call as final so a genuinely truncated tail is detected.

import codecs
d=codecs.getincrementaldecoder('utf-8')()
b='数'.encode()
[d.decode(b[:1]),d.decode(b[1:],final=True)]

Result ['', '数']

中文

UTF-8 字符跨数据块时怎样正确解码?

增量解码器保存尚未构成完整字符的字节,接到后续块时继续解码。

Python 算例与适用条件

汉字“数”的前三个 UTF-8 字节分在两块中。最后一次调用应标记流结束,让真正截断的尾部被检测出来。

import codecs
d=codecs.getincrementaldecoder('utf-8')()
b='数'.encode()
[d.decode(b[:1]),d.decode(b[1:],final=True)]

结果 ['', '数']

References / 参考来源

Keep reading / 继续阅读