gpt4 book ai didi

c - 如何在普通 C89 中读取给定字符长度的 UTF-8 字符串?

转载 作者:太空狗 更新时间:2023-10-29 17:18:43 25 4
gpt4 key购买 nike

我正在使用纯 C89 编写自定义跨平台简约 TCP 服务器。 (但我也会接受特定于 POSIX 的答案。)

服务器使用 UTF-8 字符串,但从不查看它们的内部。它将所有字符串视为不可变的二进制 blob。

但现在我需要从不知道如何以字节为单位计算大小的客户端接受 UTF-8 字符串。客户端只能传输以字符为单位的字符串长度。 (更新:客户端在 JavaScript 中,“字符长度”实际上是 String.length() 返回的任何内容。我假设它是实际的 UTF-8 字符,而不是什么否则。)

我不想向我的小型服务器添加大量依赖项。有没有一种健壮而简洁的方法来读取这个数据报? (为了这个问题,假设它是从 FILE * 中读取的。)

U<CRLF>       ; data type marker (actually read by dispatching code)
<SIZE><CRLF> ; UTF-8 string size in characters
<DATA><CRLF> ; data blob

例子:

U
7
Юникод!

更新:

一批数据可以包含多个数据报,所以近似读取是行不通的,我需要读取准确数量的字符。

而且实际的 UTF-8 数据可能包含任何字符,所以我不能选择一个字符作为终止符——我不想在数据中转义它。

最佳答案

根据信息 here 编写 UTF-8“阅读器”非常容易; UTF-8 旨在让像这样的任务变得简单。

从本质上讲,您会开始阅读字符,直到您阅读了客户告诉您的字数为止。你知道你已经阅读了给定 UTF-8 编码定义的整个字符,具体来说:

If the character is encoded by just one byte, the high-order bit is 0 and the other bits give the code value (in the range 0..127). If the character is encoded by a sequence of more than one byte, the first byte has as many leading '1' bits as the total number of bytes in the sequence, followed by a '0' bit, and the succeeding bytes are all marked by a leading "10" bit pattern.

关于c - 如何在普通 C89 中读取给定字符长度的 UTF-8 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5517205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com