.NET从hex值的字符串转换为Unicode字符(支持不同的代码页)

我有一串Hex值……

String hexString = "8A65"; 

我需要将此字符串转换为它们的Unicode等价物。 棘手的部分是我需要支持不同的代码页,一些代码页有’8A65’=一个字符,而其他代码页将它转换成两个字符。

在我需要执行转换之前,我不知道将使用哪个代码页。

我尝试过各种各样的东西,比如

 byte[] original = Encoding.Unicode.GetBytes(hexString); byte[] conv= Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding(932), orig); char[] chars = Encoding.GetEncoding(932).GetChars(conv); 

注意:代码页932是日语

 string hexString = "8A65"; int length = hexString.length; byte[] bytes = new byte[length / 2]; for (int i = 0; i < length; i += 2) { bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16); } char[] chars = Encoding.GetEncoding(932).GetChars(bytes); 

谢谢pstrjds,你是一个救生员!

您需要将hex字符串转换为字节(请参阅SOpost )。 将hex字符串传递给其中一个编码以将其转换为字节只会为您提供与这些字符等效的字节。 我假设您想要的是4个字符串表示的两个字节,因此将hex解码为字节,然后您可以使用解码字节上的编码来获取字符串。

 Encoding.{YourEncoding}.GetChars(hexBytes); 
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; class Sample { static public void Main(){ var data = "8A65"; Regex regex = new Regex(@"(?[0-9A-F]{2})",RegexOptions.IgnoreCase | RegexOptions.Compiled); byte[] bytes = regex.Matches(data).OfType().Select(m => Convert.ToByte(m.Groups["hex"].Value,16)).ToArray(); char[] chars = Encoding.GetEncoding(932).GetChars(bytes); Console.WriteLine(new String(chars)); } }