gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:58:09 28 4
gpt4 key购买 nike

我有一个字节数组,我相信它可以正确存储 Unicode 字符的 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 位

最佳答案

Encoding.Unicode是基于每个 UTF-16 代码单元的 little-endian。您仍然需要将高代理代码单元放在低代理代码单元之前。这是有效的示例代码:

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
}
}

关于c# - 将 UTF-16 字节数组编码为字符串字符 C# .NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61044444/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com