First we examine the PHP. I'm rustier with that than C#, but it is first breaking off chunks of two-characters, then parsing that as hexadecimal, then creating a character from that, and adding it to that produced.
If we are to assume that the string is always ASCII, and hence there is no encoding problem, we can do the same in C# as follows:
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.
}
Alternatively, if we have to deal with another encoding, we can take a different approach. We'll use UTF-8 as our example, but it follows with any other encoding (the following will also work in the above case of ASCII-only, since it matches UTF-8 for that range):
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.
}