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

时间:2010-09-24 13:02:16

标签: c decoding utf-16

我的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;
}

它是如何运作的?

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

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

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

问题?

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

最后一个有效的Unicode代码点

U+10FFFD在UTF-16中编码为0xDBFF 0xDFFD。我们试着解码一下。

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

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

在计算器中

gcalctool 中手动执行所有转换会产生相同的错误答案。所以我的语法本身并没有错,但算法是。这个算法对我来说似乎是正确的,但它却以错误的答案结束。

我做错了什么?

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

您似乎错过了0x10000的偏移量。

根据this WIKI page,UTF-16代理对的构造如下:

  

UTF-16表示非BMP字符   (U + 10000到U + 10FFFF)使用两个   代码单元,称为代理对。   从中减去第一个10000 16   代码指向一个20位的值。   然后将其拆分为两个10位   每个值表示为   一个最重要的代理人   一半放在第一个代理人身上。