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

D P*_* P. 4 c# decode visual-studio-2010

我正在尝试将字符串中的十六进制值转换为 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");
Run Code Online (Sandbox Code Playgroud)

Dav*_*yon 6

由于您正在命名一个变量hexString,我假设该值已经编码为十六进制格式。

这意味着以下内容将不起作用:

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

这是因为您将已编码的字符串视为纯 UTF8 文本。

您可能缺少将十六进制编码字符串转换为字节数组的步骤。

您可以使用此 SO 帖子来执行此操作,该帖子显示了此功能:

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;
}
Run Code Online (Sandbox Code Playgroud)

所以,最终结果将是这样的:

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");
Run Code Online (Sandbox Code Playgroud)