gpt4 book ai didi

c# - 在 C# 字符串/字符编码中,GetBytes()、GetString() 和 Convert() 之间有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 22:29:21 24 4
gpt4 key购买 nike

我们无法将 Unicode 字符串转换为 UTF-8 字符串以通过网络发送:

// Start with our unicode string.
string unicode = "Convert: \u10A0";

// Get an array of bytes representing the unicode string, two for each character.
byte[] source = Encoding.Unicode.GetBytes(unicode);

// Convert the Unicode bytes to UTF-8 representation.
byte[] converted = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, source);

// Now that we have converted the bytes, save them to a new string.
string utf8 = Encoding.UTF8.GetString(converted);

// Send the converted string using a Microsoft function.
MicrosoftFunc(utf8);

虽然我们已经将字符串转换为 UTF-8,但它并没有以 UTF-8 的形式到达。

最佳答案

经过一个早上的困扰和困惑,我们找到了这个问题的答案。

我们遗漏的关键点是字符串类型始终以 16 位(2 字节)Unicode 编码,这让这变得非常困惑。这意味着当我们对字节执行 GetString() 操作时,它们在幕后会自动重新编码为 Unicode,我们的情况并没有比最初更好。

当我们开始出现字符错误,另一端出现双字节数据时,我们知道出了点问题,但扫一眼我们的代码,我们看不出有什么问题。在了解了我们上面的解释之后,我们意识到如果我们想保留编码,我们需要发送字节数组。幸运的是,MicrosoftFunc() 有一个重载,它能够接受字节数组而不是字符串。这意味着我们可以将 unicode 字符串转换为我们选择的编码,然后完全按照我们的预期发送它。代码改为:

// Convert from a Unicode string to an array of bytes (encoded as UTF8).
byte[] source = Encoding.UTF8.GetBytes(unicode);

// Send the encoded byte array directly! Do not send as a Unicode string.
MicrosoftFunc(source);

总结:

所以综上所述,从上面我们可以看出:

  • GetBytes() 除其他事项外,从 Unicode (因为字符串始终是 Unicode) 执行 Encoding.Convert() 并从中调用函数的指定编码和返回一个编码字节数组。
  • GetString() 除其他外,执行 Encoding.Convert() 从调用函数的指定编码到 Unicode (因为字符串始终是 Unicode) 和将其作为字符串对象返回。
  • Convert() 实际上是将一种编码的字节数组转换为另一种编码的字节数组。显然不能使用字符串(因为字符串总是Unicode)

关于c# - 在 C# 字符串/字符编码中,GetBytes()、GetString() 和 Convert() 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1426733/

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