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