UTF-16解码器无法按预期工作

Del*_*ani 5 c utf-16 decoding

我有一部分我的Unicode库将UTF-16解码为原始的Unicode代码点.但是,它没有按预期工作.

这是代码的相关部分(省略UTF-8和字符串操作):

typedef struct string {
    unsigned long length;
    unsigned *data;
} string;

string *upush(string *s, unsigned c) {
    if (!s->length) s->data = (unsigned *) malloc((s->length = 1) * sizeof(unsigned));
    else            s->data = (unsigned *) realloc(s->data, ++s->length * sizeof(unsigned));
    s->data[s->length - 1] = c;
    return s;
}

typedef struct string16 {
    unsigned long length;
    unsigned short *data;
} string16;

string u16tou(string16 old) {
    unsigned long i, cur = 0, need = 0;
    string new;
    new.length = 0;
    for (i = 0; i < old.length; i++)
        if (old.data[i] < 0xd800 || old.data[i] > 0xdfff) upush(&new, old.data[i]);
        else
            if (old.data[i] > 0xdbff && !need) {
                cur = 0; continue;
            } else if (old.data[i] < 0xdc00) {
                need = 1;
                cur = (old.data[i] & 0x3ff) << 10;
                printf("cur 1: %lx\n", cur);
            } else if (old.data[i] > 0xdbff) {
                cur |= old.data[i] & 0x3ff;
                upush(&new, cur);
                printf("cur 2: %lx\n", cur);
                cur = need = 0;
            }
    return new;
}
Run Code Online (Sandbox Code Playgroud)

它是如何工作的?

string是一个包含32位值的结构,string16用于16位值,如UTF-16.所有upush这一切都是为a添加一个完整的Unicode代码点string,根据需要重新分配内存.

u16tou是我关注的部分.它循环通过string16,正常传递非代理值,并将代理对转换为完整代码点.错位的代理被忽略了.

一对中的第一个代理具有最低10位向左移位10位,导致它形成最终代码点的高10位.另一个代理人将最低的10位添加到最后,然后将其附加到字符串.

问题?

让我们尝试最高的代码点,好吗?

U+10FFFD,最后一个有效的Unicode代码点,编码为0xDBFF 0xDFFDUTF-16.我们来试试吧.

string16 b;
b.length = 2;
b.data = (unsigned short *) malloc(2 * sizeof(unsigned short));
b.data[0] = 0xdbff;
b.data[1] = 0xdffd;
string a = u16tou(b);
puts(utoc(a));
Run Code Online (Sandbox Code Playgroud)

使用utoc(未显示;我知道它正在工作(见下文))函数将其转换回UTF-8 char *进行打印,我可以在我的终端中看到我得到的结果U+0FFFFD,而不是U+10FFFD结果.

在计算器中

gcalctool中手动执行所有转换导致相同的错误答案.所以我的语法本身并没有错,但算法是.算法对我来说似乎是正确的,但它的结尾却是错误的答案.

我究竟做错了什么?

Jos*_*phH 5

解码代理对时需要加上0x10000; 引用rfc 2781,你缺少的步骤是5号:

    1) If W1 < 0xD800 or W1 > 0xDFFF, the character value U is the value
       of W1. Terminate.

    2) Determine if W1 is between 0xD800 and 0xDBFF. If not, the sequence
       is in error and no valid character can be obtained using W1.
       Terminate.

    3) If there is no W2 (that is, the sequence ends with W1), or if W2
       is not between 0xDC00 and 0xDFFF, the sequence is in error.
       Terminate.

    4) Construct a 20-bit unsigned integer U', taking the 10 low-order
       bits of W1 as its 10 high-order bits and the 10 low-order bits of
       W2 as its 10 low-order bits.

    5) Add 0x10000 to U' to obtain the character value U. Terminate.

即.一次修复是在第一次阅读后添加一行:

cur = (old.data[i] & 0x3ff) << 10;
cur += 0x10000;
Run Code Online (Sandbox Code Playgroud)