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

标签 c# visual-studio-2010 decode

我正在尝试将字符串中的十六进制值同时转换为 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");

最佳答案

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

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

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

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

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

您可以使用 this 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");

关于C# 将十六进制值转换为 UTF8 和 ASCII,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19024925/

相关文章:

c# - Math.Round() 为 double 产生意想不到的结果

c# - Microsoft 云服务/辅助角色部署 - 未找到方法?

c# - 使用 Entity Framework ,返回 DateTime 列的日期端口等于今天的所有行

c++ - 使用带有 std::unique_ptr 的抽象删除器

firefox - 从十六进制格式解码 Firefox 浏览器缓存条目

python - 使用python从JSON文件中提取部分数据

c# - 如何将 switch 语句的结果存储到 C# 中的对象中

c# - 如何将 IQueryable 转换为 DataTable

visual-studio-2010 - Visual Studio 2010 中的 Razor 模板编辑 : why all the type inference errors?

c++ - HEX 的编码类型