如何在C#中获取Unicode字符的十六进制表示?

时间:2014-04-02 14:57:47

标签: c# string unicode

这是我的代码:

var hexString = BitConverter.ToString(Encoding.Unicode.GetBytes("ABCD"));

hexString = Regex.Replace(hexString, "[-]", string.Empty);

我得到了结果:

4100420043004400

我应该得到:

0041004200430044

这看起来像一个尾随,以“00”结尾的问题但我在尝试使用特殊字符时实际上遇到了其他错误。

例如希腊字母Ο

应该是039f,但我的代码会给我9F03

我甚至尝试过在另一个问题中找到的以下代码:

public static string ByteArrayToString(byte[] ba)
{
    StringBuilder hex = new StringBuilder(ba.Length * 2);
    foreach (byte b in ba)
        hex.AppendFormat("{0:x2}", b);
    return hex.ToString();
}

结果是一样的。

1 个答案:

答案 0 :(得分:3)

您在Little Endian中获得了Unicode编码。

尝试Encoding.BigEndianUnicode - 它会为您提供您想要的内容(例如0041004200430044代表'ABCD') - 只需将Unicode更改为BigEndianUnicode。