# Convert between byte arrays and hexadecimal strings in C# 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;

// 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. ### 2 Responses to Convert between byte arrays and hexadecimal strings in C#

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.
{"ft_lang_label":"__label__en","ft_lang_prob":0.5099623,"math_prob":0.75601983,"size":3833,"snap":"2021-04-2021-17","text_gpt3_token_len":780,"char_repetition_ratio":0.18359885,"word_repetition_ratio":0.056239016,"special_character_ratio":0.21732324,"punctuation_ratio":0.12703101,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.950085,"pos_list":[0,1,2,3,4,5,6,7,8],"im_url_duplicate_count":[null,1,null,null,null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-04-20T20:46:34Z\",\"WARC-Record-ID\":\"<urn:uuid:766aa51d-97be-4e7d-9dbe-bdde2edc8957>\",\"Content-Length\":\"56877\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:d303bc5f-45ac-4e09-ae93-c189820262ec>\",\"WARC-Concurrent-To\":\"<urn:uuid:4be50724-6d93-42cd-9a99-89d496481920>\",\"WARC-IP-Address\":\"107.180.57.98\",\"WARC-Target-URI\":\"http://csharphelper.com/blog/2014/09/convert-between-byte-arrays-and-hexadecimal-strings-in-c/\",\"WARC-Payload-Digest\":\"sha1:ROKVW7X5X6RVHJGFJ7GIJ57FG6KQUFFG\",\"WARC-Block-Digest\":\"sha1:QZKCCBMO7QVIFVYFBF2L36ZDGMLLUZS4\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-17/CC-MAIN-2021-17_segments_1618039490226.78_warc_CC-MAIN-20210420183658-20210420213658-00469.warc.gz\"}"}