您的位置:首页 > 其它

UTF-8编码转换实现

2010-12-26 12:23 204 查看
/////////////////

UTF-8 转换原理
U-00000000 - U-0000007F: 0xxxxxxx
U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx

//以下摘自D7的VCL源程序~

第一个字节的开头"1"的数目就是整个串中字节的数目

if c <= $7F then
begin
{
U-00000000 - U-0000007F: 0xxxxxxx
1个字节的直接复制
}
Dest[count] := AnsiChar(c);
Inc(count);
end
else if c > $7FF then
begin
{
U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx
3个字节的分开处理, 上面可以放X的位置是 4+6+6 个,
第一个字节只放 四个 XXXX, 所以要将后 原始内容 后移 6+6位,然后与 11100000B(E0) or运算.
第二个字节在将原始内容后移6位,然后与 111111B and运算,这样就去掉了原始内容前面的位,只保留想要的中间6位,
将这个内容再与 10000000B or 运算.
第三个字节与第二个字节的思路一样,只是不用再移位了.
}
if count + 3 > MaxDestBytes then
break;
Dest[count] := AnsiChar($E0 or (c shr 12));
Dest[count+1] := AnsiChar($80 or ((c shr 6) and $3F));
Dest[count+2] := AnsiChar($80 or (c and $3F));
Inc(count,3);
end
else // $7F < Source[i] <= $7FF
begin
if count + 2 > MaxDestBytes then
break;
Dest[count] := AnsiChar($C0 or (c shr 6));
Dest[count+1] := AnsiChar($80 or (c and $3F));
Inc(count,2);
end;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: