【问题标题】:Convert text utf8 to char or string将文本 utf8 转换为 char 或 string
【发布时间】:2013-10-30 08:27:25
【问题描述】:

现在我有文本 = “0e2a0e270e310e2a0e140e350e040e230e310e1a”可以转换为“สวัสดีครับ” 我在这里使用 C# 代码

string unicodeString = "0e2a0e270e310e2a0e140e350e040e230e310e1a";
// Create two different encodings.
Encoding utf8 = Encoding.UTF8;
Encoding unicode = Encoding.Unicode;

// Convert the string into a byte[].
byte[] unicodeBytes = unicode.GetBytes(unicodeString);

// Perform the conversion from one encoding to the other.
byte[] utf8Bytes = Encoding.Convert(unicode, utf8, unicodeBytes);

// Convert the new byte[] into a char[] and then into a string.
// This is a slightly different approach to converting to illustrate
// the use of GetCharCount/GetChars.

char[] asciiChars = new char[utf8.GetCharCount(utf8Bytes, 0, utf8Bytes.Length)];
utf8.GetChars(utf8Bytes, 0, utf8Bytes.Length, asciiChars, 0);
string asciiString = new string(asciiChars);

return asciiString;

没用

【问题讨论】:

  • 定义“不工作”;发生什么了?另外:你为什么期望"0e2a0e270e310e2a0e140e350e040e230e310e1a" 变成"0e2a0e270e310e2a0e140e350e040e230e310e1a" 以外的任何东西?
  • 顺便说一句,你在哪里看到任何 ASCII?
  • 这不能转换为“สวัสดีครับ”
  • this add \u in text 可以转换,但我不知道如何在字符串中添加 \u string unicodeString = "\u0e2a\u0e27\u0e31\u0e2a\u0e14\u0e35\u0e04\u0e23\u0e31 \u0e1a";可以转换成“สวัสดีครับ”谢谢

标签: c# text encoding


【解决方案1】:

输入是十六进制,而不是 unicode - 编码是 big-endian utf-16:

string hexString = "0e2a0e270e310e2a0e140e350e040e230e310e1a";

// unscramble the hex
byte[] bytes = new byte[hexString.Length / 2];
for(int i = 0; i < bytes.Length; i++)
{
    bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}

// convert to a string via big-endian utf-16
string result = Encoding.BigEndianUnicode.GetString(bytes); // "สวัสดีครับ"

【讨论】:

    猜你喜欢
    • 2011-01-26
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 2011-08-01
    • 2010-10-12
    • 1970-01-01
    相关资源
    最近更新 更多