C#将十六进制值转换为UTF8和ASCII

4

我想将一个包含十六进制值的字符串转换为ASCII值和UTF8值。但是当我执行以下代码时,它输出与我输入的相同的十六进制值。

string hexString = "68656c6c6f2c206d79206e616d6520697320796f752e";
System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
byte[] dBytes = encoding.GetBytes(hexString);

//To get ASCII value of the hex string.
string ASCIIresult = System.Text.Encoding.ASCII.GetString(dBytes);
MessageBox.Show(ASCIIresult, "Showing value in ASCII");

//To get the UTF8 value of the hex string
string utf8result = System.Text.Encoding.UTF8.GetString(dBytes);
MessageBox.Show(utf8result, "Showing value in UTF8");

1
您是否遗漏了将 hexString 转换为字节的步骤? - Davin Tryon
3个回答

6
由于您将变量命名为hexString,我假设该值已经编码为十六进制格式。
这意味着以下内容将无法正常工作:
string hexString = "68656c6c6f2c206d79206e616d6520697320796f752e";
System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
byte[] dBytes = encoding.GetBytes(hexString);

这是因为您将已编码的字符串视为普通的UTF8文本。
您可能错过了将十六进制编码的字符串转换为字节数组的步骤。
您可以使用此SO post中显示的函数进行转换:
public static byte[] StringToByteArray(String hex)
{
  int NumberChars = hex.Length/2;
  byte[] bytes = new byte[NumberChars];
  using (var sr = new StringReader(hex))
  {
    for (int i = 0; i < NumberChars; i++)
      bytes[i] = 
        Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);
  }
  return bytes;
}

那么,最终结果应该是这样的:
byte[] dBytes = StringToByteArray(hexString);

//To get ASCII value of the hex string.
string ASCIIresult = System.Text.Encoding.ASCII.GetString(dBytes);
MessageBox.Show(ASCIIresult, "Showing value in ASCII");

//To get the UTF8 value of the hex string
string utf8result = System.Text.Encoding.UTF8.GetString(dBytes);
MessageBox.Show(utf8result, "Showing value in UTF8");

1
非常感谢大家提供如此详细的答案,真的帮了我很多。 - D P.

4
你需要首先将十六进制字符串转换为字节数组:
byte[] dBytes = Enumerable.Range(0, hexString.Length)
                 .Where(x => x % 2 == 0)
                 .Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
                 .ToArray();

0

我已经使用了这种方法来转换任何

public static string FromHex (string h) //Put your sequence of hex to convert to string.
{
    if (h.Length % 2 != 0) 
        throw new ArgumentException("The string " + nameof(h) + " is not a valid Hex.", nameof(h));
    char[] CharFromHex = new char[h.Length / 2];
    int j = 0;
    for (int i = 0; i < h.Length; i += 2)
    {
        string hexSubStr = h.Substring(i, 2);
        CharFromHex[j] = (char)Convert.ToInt32(hexSubStr, 16);
        j += 1;
    }
    StringBuilder str = new StringBuilder();
    str.Append(CharFromHex);
    return str.ToString();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接