将UTF-16字节数组编码成C# .NET字符串字符

5

我有一个字节数组,我相信它正确地存储了一个UTF-16编码的代理项对,用于Unicode字符。

将该字节数组通过.Net System.Text.Encoding.Unicode.GetString() 进行处理会返回不符合预期的结果。

实际结果:��

预期结果:

代码示例:

byte[] inputByteArray = new byte[4];
inputByteArray[0] = 0x91;
inputByteArray[1] = 0xDF;
inputByteArray[2] = 0x00;
inputByteArray[3] = 0xD8;

// System.Text.Encoding.Unicode accepts little endian UTF-16
// Least significant byte first within the byte array [0] MSByete in [3]
string str = System.Text.Encoding.Unicode.GetString(inputByteArray);

// This returns �� rather than the excpected symbol:  
Console.WriteLine(str);

我是如何从字符转换为特定字节数组的详细信息:

这个字符在补充多语言平面中。该字符的Unicode编码为0x10391。将其编码为UTF-16代理对,应该是:

用Unicode值减去0x10000:val = 0x00391 = (0x10391 - 0x10000)

高代理项:0xD800 = ( 0xD800 + (0x00391 >> 10 )) 前10位

低代理项:0xDF91 = (0xDC00 + (0x00391 & 0b_0011_1111_1111)) 后10位

1个回答

6

Encoding.Unicode每个 UTF-16 代码单元的 基础上是小端序的。您仍然需要将高代理项代码单元放在低代理项代码单元之前。以下是可行的示例代码:

using System;
using System.Text;

class Test
{
    static void Main()
    {
        byte[] data =
        {
            0x00, 0xD8, // High surrogate
            0x91, 0xDF  // Low surrogate
        };
        string text = Encoding.Unicode.GetString(data);
        Console.WriteLine(char.ConvertToUtf32(text, 0)); // 66449
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接