The easiest Hex string to/from byte array I've found
When looking for a utility function to convert from a hex string to a byte array, I found this example .. works a treat!
http://programmerramblings.blogspot.com/2008/03/convert-hex-string-to-byte-array-and.html
Code
/// <SUMMARY>
/// Convert string to byte_array
/// </SUMMARY>
/// <PARAM name="strInput"></PARAM>
private byte[] String_To_Bytes(string strInput)
{
// i variable used to hold position in string
int i = 0;
// x variable used to hold byte array element position
int x = 0;
// allocate byte array based on half of string length
byte[] bytes = new byte[(strInput.Length) / 2];
// loop through the string - 2 bytes at a time converting it to decimal equivalent
// and store in byte array
while (strInput.Length > i + 1)
{
long lngDecimal = Convert.ToInt32(strInput.Substring(i, 2), 16);
bytes[x] = Convert.ToByte(lngDecimal);
i = i + 2;
++x;
}
// return the finished byte array of decimal values
return bytes;
}
/// <SUMMARY>
/// Convert byte_array to string
/// </SUMMARY>
/// <PARAM name="bytes_Input"></PARAM>
private string Bytes_To_String(byte[] bytes_Input)
{
// convert the byte array back to a true string
string strTemp = "";
for (int x = 0; x <= bytes_Input.GetUpperBound(0); x++)
{
int number = int.Parse(bytes_Input[x].ToString());
strTemp += number.ToString("X").PadLeft(2, '0');
}
// return the finished string of hex values
return strTemp;
}
| Author |
: Paul Hayman |
| Published |
: Friday, 18 April, 2008 |
Paul is the COO of kwiboo ltd consultant and has more than a decade of IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.
Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.