Write extension methods to convert between byte arrays and strings of hexadecimal values in C#

An extension method is a method that you add to an existing data type. This example adds a ToHex method to the byte[] type and a ToBytes 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 determines the class to which the method applies.

The following code shows the byte[] type's new ToHex 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, optionally
// separated by spaces.
public static string ToHex(this byte[] the_bytes, bool add_spaces)
{
string result = "";
string separator = "";
if (add_spaces) separator = " ";
for (int i = 0; i < the_bytes.Length; i++)
{
result += the_bytes[i].ToString("x2") + separator;
}
return result;
}

The ToHex method loops through the array's bytes adding 2-digit hexadecimal representations of each to the result string.

The following code shows the string class's new ToBytes method.

// Convert a string containing 2-digit hexadecimal values into a byte array.
public static byte[] ToBytes(this string the_string)
{
// Remove any spaces.
the_string = the_string.Replace(" ", "");

// Allocate room for the bytes.
byte[] bytes = new byte[the_string.Length / 2];

// Parse the letters in pairs.
int byte_num = 0;
for (int i = 0; i < the_string.Length; i += 2)
{
bytes[byte_num++] =
byte.Parse(the_string.Substring(i, 2),
System.Globalization.NumberStyles.HexNumber);
}
return bytes;
}

This method removes any spaces from the string. It allocates room for the bytes and loops through the string, parsing pairs of characters into the array.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.