Introduction
While the .NET framework provides methods to convert a byte array into a Hexadecimal string ( byte.ToString(�X�)
), it is not so easy to convert a hexadecimal string back into a byte array. Such a function is useful when you need to backup data from your application on paper, such as an encryption key, and later, convert it back into data after the user types it in.
The HexEncoding
class provided here, contains functions which allow for the conversion of a string in hexadecimal format into a byte array, and back. It also contains functions which lets you check the formatting of the string before conversion, and how many bytes a given string will produce.
Background
In a hexadecimal string, one byte is represented two hexadecimal characters. A hexadecimal character has a value of (A-F, 0-9).
e.g. string �01FFA0� is equivalent to byte[] { 1, 255, 160 }
Using the code
HexEncoding is the name of the class I created with static functions for hexadecimal string conversion.
Here�s a sample of how it is used, when the Convert button is clicked like on the screenshot:
private void button1_Click(object sender, System.EventArgs e)
{
string hexString = txtHex.Text;
int discarded;
txtByteCount.Text = ((int)HexEncoding.GetByteCount(hexString)).ToString();
txtLength.Text = hexString.Length.ToString();
byte[] byteArray = HexEncoding.GetBytes(hexString, out discarded);
txtDiscard.Text = discarded.ToString();
string temp = "";
for (int i=0; i<byteArray.Length; i++)
{
temp += byteArray[i].ToString("D3") + " ";
}
txtByte.Text = temp;
txtHex2.Text = HexEncoding.ToString(byteArray);
}
HexEncoding
.GetByteCount(string hexString)
returns the number of bytes that will be generated from the hexString.
HexEncoding.GetBytes(string hexString, out int discarded)
returns the byte array converted from the hexString, and the second parameter returns the number of non-hexadecimal characters that were ignored in the string. This includes dashes, whitespace, and letters after �F�.
HexEncoding.ToString(byte[])
returns the newly converted byte array back into string form. Notice the �-� characters are now missing.
The key function provided by the framework to convert a hexadecimal string to a single byte is this:
where �hex� is of the form �1A�, �00�, �FF�, etc.
Thanks to Polux on the .NET 247 newsgroups who posted the int.Parse(...)
answer to another hexadecimal question.