在 C# 中将十六进制字符串解码为字符串,就像这个 php 代码一样


Decode hex-string to a string in C# like this php code

// This function converts from a hexadecimal representation to a string representation.
function hextostr($hex) {
  $string = "";
  foreach (explode("'n", trim(chunk_split($hex, 2))) as $h) {
    $string .= chr(hexdec($h));
  }
 return $string;
 }

我将如何在 c# 中做完全相同的事情?

它适用于支付提供商,仅提供 php 格式的示例代码。

首先,我们检查PHP。我比 C# 更生疏,但它首先分解两个字符的块,然后将其解析为十六进制,然后从中创建字符,并将其添加到生成的字符中。

如果我们假设字符串始终是 ASCII,因此不存在编码问题,我们可以在 C# 中执行相同的操作,如下所示:

public static string HexToString(string hex)
{
  var sb = new StringBuilder();//to hold our result;
  for(int i = 0; i < hex.Length; i+=2)//chunks of two - I'm just going to let an exception happen if there is an odd-length input, or any other error
  {
    string hexdec = hex.Substring(i, 2);//string of one octet in hex
    int number = int.Parse(hexdec, NumberStyles.HexNumber);//the number the hex represented
    char charToAdd = (char)number;//coerce into a character
    sb.Append(charToAdd);//add it to the string being built
  }
  return sb.ToString();//the string we built up.
}

或者,如果我们必须处理另一种编码,我们可以采取不同的方法。我们将使用 UTF-8 作为示例,但它遵循任何其他编码(以下内容也适用于上述仅 ASCII 的情况,因为它与该范围内的 UTF-8 匹配(:

public static string HexToString(string hex)
{
  var buffer = new byte[hex.Length / 2];
  for(int i = 0; i < hex.Length; i+=2)
  {
    string hexdec = hex.Substring(i, 2);
    buffer[i / 2] = byte.Parse(hexdec, NumberStyles.HexNumber);
  }
  return Encoding.UTF8.GetString(buffer);//we could even have passed this encoding in for greater flexibility.
}

根据此链接:

public string ConvertToHex(string asciiString)
{ 
    string hex = "";
    foreach (char c in asciiString)
    {
        int tmp = c;
        hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
    }
    return hex;
}

你尝试用这个代码

var input = "";
String.Format("{0:x2}", System.Convert.ToUInt32(input))