【问题标题】:Decode hex-string to a string in C# like this php code将十六进制字符串解码为 C# 中的字符串,就像这个 php 代码一样
【发布时间】:2012-08-29 20:16:32
【问题描述】:
// 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中的示例代码。

【问题讨论】:

  • 明确一点,十六进制表示已经是一个字符串。 “将十六进制转换为字符串”可以更改为更合适的内容。

标签: c# php hex


【解决方案1】:

首先我们检查 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.
}

【讨论】:

  • 字符串 hexdec 未在两个函数的第一个中使用。这是故意的,还是应该在下一行使用?
  • 这是第一个函数中的错字,被复制粘贴到第二个函数中。固定。
  • 完美运行。谢谢@JonHanna
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    你试试这个代码

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

    【讨论】:

      猜你喜欢
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 2012-06-29
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      相关资源
      最近更新 更多