Hex Encode/Decode String In C#

The same code is posted all over the news groups and Internet, but here it is, easy as a snippet for myself and for you to use.

I don’t even get credit for this as what I have pretty much matches up to what other people have already posted.

This is much easier in Python.

Encode a byte array
[code language=”csharp”]
public static string HexEncode(byte[] data)
{
return BitConverter.ToString(data).Replace(“-“, string.Empty);
}
[/code]

Decode a hex necoded string
[code language=”csharp”]
public static byte[] HexDecode(string hexEncoded)
{
int numChars = hexEncoded.Length;
byte[] retVal = new byte[numChars / 2];
for (int i = 0; i < numChars; i += 2) { retVal[i / 2] = Convert.ToByte(hexEncoded.Substring(i, 2), 16); } return retVal; } [/code]

This entry was posted in C#, Snippets and tagged . Bookmark the permalink.

Leave a Reply

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