C# Converting hexadecimal string to/from byte array, FAST!
I previously wrote about how to quickly convert a byte array to its hex representation and back again in C. Now I’ve converted the same source code to C#. Even though there is a built in method using String.Format, it is too slow.
public static string ByteArrayToHexString(byte[] Bytes)
{
StringBuilder Result;
string HexAlphabet = “0123456789ABCDEF”;
Result = new StringBuilder();
foreach (byte B in Bytes)
{
Result.Append(HexAlphabet[(int)(B >> 4)]);
Result.Append(HexAlphabet[(int)(B & 0xF)]);
}
return Result.ToString();
}
public static byte[] HexStringToByteArray(string Hex)
{
byte[] Bytes;
int ByteLength;
string HexValue = “\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9|||||||\xA\xB\xC\xD\xE\xF”;
ByteLength = Hex.Length / 2;
Bytes = new byte[ByteLength];
for (int x = 0, i = 0; i < Hex.Length; i += 2, x += 1)
{
Bytes[x] = (byte)(HexValue[Char.ToUpper(Hex[i + 0]) - '0'] << 4);
Bytes[x] |= (byte)(HexValue[Char.ToUpper(Hex[i + 1]) - '0']);
}
return Bytes;
}








