C# Converting hexadecimal string to/from byte array, FAST!
June 26th, 2008
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;
}









July 13th, 2008 at 3:59 am
For a 3MB file it threw a OutOfMemoryException with the following details:
System.OutOfMemoryException was unhandled
Message=”Exception of type ‘System.OutOfMemoryException’ was thrown.”
Source=”mscorlib”
StackTrace:
at System.String.GetStringForStringBuilder(String value, Int32 startIndex, Int32 length, Int32 capacity)
at System.Text.StringBuilder.GetNewString(String currentString, Int32 requiredLength)
at System.Text.StringBuilder.Append(Char value)
at BinaryFileNamespace.BinaryFile.ByteArrayToHexString(Byte[] bytes) in Binary File.cs:line 41
at BinaryFileNamespace.BinaryFile..ctor(String fileFullPath) in Binary File.cs:line 31
at Video_Compression_Project.Form1.Form1_Load(Object sender, EventArgs e) in Form1.cs:line 28
at System.Windows.Forms.Form.OnLoad(EventArgs e)
July 13th, 2008 at 11:59 am
You need to adapt the function yourself to work with files. The algorithm itself works. Converting a 3MB file to a string is probably not the best idea.
August 5th, 2008 at 7:30 am
I’ve been working on hex -> byte , byte -> hex for a while, but yours is much simpler… Thanks for sharing your sample.