Convert between byte arrays and hexadecimal strings in C#

Convert between byte arrays and hexadecimal strings

This example uses extension methods to convert between byte arrays and hexadecimal strings. It adds a ToHex extension method to the byte[] type and a ToBytes extension method to the string class.

To create an extension method, create a public static class. Give it methods where the first parameter’s declaration starts with the this keyword. That parameter’s type determines the class to which the method applies.

The following code shows the byte[] type’s ToHex extension method. Notice how the first parameter has the this keyword and has type byte[].

// Return a string that represents the byte array
// as a series of hexadecimal values separated
// by a separator character.
public static string ToHex(this byte[] the_bytes, char separator)
{
    return BitConverter.ToString(
        the_bytes, 0).Replace('-', separator);
}

This method calls BitConverter.ToString to convert the byte array into a string that contains two-digit hexadecimal values in the format 54-00-6F-00-20. The code uses the string class’s Replace method to replace the hyphens with the desired separator character.

Unfortunately the BitConverter class doesn’t have a reverse method that converts a string of the form 54-00-6F-00-20 back into a byte array, so you need to write your own. Fortunately, that’s not hard. The following code shows the string class’s ToBytes extension method.

// Convert a string containing 2-digit hexadecimal
// values into a byte array.
public static byte[] ToBytes(this string the_string)
{
    // Get the separator character.
    char separator = the_string[2];

    // Split at the separators.
    string[] pairs = the_string.Split(separator);
    byte[] bytes = new byte[pairs.Length];
    for (int i = 0; i < pairs.Length; i++)
        bytes[i] = Convert.ToByte(pairs[i], 16);
    return bytes;
}

This method assumes the string consists of two-digit hexadecimal values separated by a separator character. It uses the string's third character as the separator. It then uses the string class's Split method to split the string at the separators.

The code then loops through the hexadecimal values, uses Convert.ToByte to convert each back into a byte value, and saves the results into the bytes array. When it finishes, the method returns that array.

When you click the left > button, the program uses the following code to convert a string into a hexadecimal representation.

// Convert the string into an array of bytes and display it.
private void btnToHexString_Click(object sender, EventArgs e)
{
    // Convert the string into bytes.
    UnicodeEncoding ascii_encoder = new UnicodeEncoding();
    byte[] bytes = ascii_encoder.GetBytes(txtOriginal.Text);

    // Display the result as a string of hexadecimal values.
    txtHexadecimal.Text = bytes.ToHex(' ');
}

This code uses the System.Text.UnicodeEncoding object to convert the string into a byte array. It then uses the ToHex extension method to convert the array into a string and displays the result.

When you click the right > button, the program uses the following code to convert the hexadecimal representation back into a string.

// Converrt the string of hexadecimal values back into a string.
private void btnToString_Click(object sender, EventArgs e)
{
    // Convert the string of hexadecimal values
    // into an array of bytes.
    byte[] bytes = txtHexadecimal.Text.ToBytes();

    // Convert the bytes into a string and display the result.
    UnicodeEncoding ascii_encoder = new UnicodeEncoding();
    txtConvertedBack.Text = ascii_encoder.GetString(bytes);
}

This code gets the hexadecimal string representation and uses the ToBytes extension method to convert it into a byte array. It then creates a System.Text.UnicodeEncoding object's GetString method to converrt the byte array back into a string.


Download Example   Follow me on Twitter   RSS feed




This entry was posted in algorithms, cryptography, extensions, strings and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Convert between byte arrays and hexadecimal strings in C#

  1. Pingback: Encrypt or decrypt files in C# -

Leave a Reply

Your email address will not be published. Required fields are marked *