Hex String to byte array converter
C#, C# Language March 22nd, 2006The following simple static class will take a string of Hexdecimal characters and convert it to a byte array.
static class HexStringConverter
{
public static byte[] ToByteArray(String HexString)
{
int NumberChars = HexString.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
}
return bytes;
}
}
January 6th, 2008 at 6:18 am
Works perfectly, thanks.
February 4th, 2008 at 11:04 am
What is the licence for that code snippet ? Can I reuse it ? If yes, can I reuse it in an internal (i.e. within my company) code ? In a commercial product ?
–
BBa
February 4th, 2008 at 1:07 pm
see http://www.thinksharp.org/?page_id=81
Feel free to use in commercial software.
April 1st, 2008 at 9:24 pm
sigh, stupid html check.
for (int i = 0; i < NumberChars; i += 2)
{
try
{
bytes[i / 2] = Convert.ToByte(Hex.Substring(i, 2), 16);
}
catch
{
//failed to convert these 2 chars, they may contain illegal charracters
bytes[i / 2] = 0;
}
}
return bytes;
}
* fixes uneven number of hex characters by adding a zero in front of the string
* handles illegal characters gracefully
(admin, feel free to merge my posts)
April 2nd, 2008 at 7:29 am
Thanks Peter. Use Peter’s version if you don’t want invalid strings reporting.
All feedback always welcome :)
July 14th, 2008 at 1:10 am
I use:
String _Input = “DEADBEEF LOL!!! 10101″;
Byte[] _Value = new Byte[_Input.Length / 2];
for(Int32 _Index = 0; _Index < _Value.Length; _Index++)
{
Byte.TryParse(_Input.Substring(_Index * 2, 2), System.Globalization.System.Globalization.NumberStyles.HexNumber, null, out _Value[_Index]);
}
//_Value = Byte[] {0xDE, 0xAD, 0xBE, 0xEF, 0×00, 0×00, 0×00, 0×00, 0×10, 0×10};
That way no exceptions are thrown and if the contains invalid data it will be filled with 0×00.