1
// 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.ini 中提供示例代码。

4

3 回答 3

2

首先我们检查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.
}
于 2012-08-29T20:43:34.007 回答
0

根据链接:

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;
}
于 2012-08-29T20:17:42.117 回答
0

您尝试使用此代码

var input = "";
String.Format("{0:x2}", System.Convert.ToUInt32(input))
于 2012-08-29T20:19:03.770 回答