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

时间:2012-08-29 20:16:33

标签: c# php hex

// 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中的示例代码。

3 个答案:

答案 0 :(得分: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.
}

答案 1 :(得分:0)

根据this链接:

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;
}

答案 2 :(得分:0)

您尝试使用此代码

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