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

问题描述 投票:0回答:1

我有一个字节数组,我相信它可以为Unicode字符correctly正确存储UTF-16编码的代理对𐎑

通过.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代理对,应为:

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

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

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

c# .net unicode encoding utf-16
1个回答
0
投票

Encoding.Unicode是基于per-UTF-16代码单元

© www.soinside.com 2019 - 2024. All rights reserved.