Click here to Skip to main content
Licence 
First Posted 6 May 2003
Views 604,992
Bookmarked 95 times

Converting Hexadecimal String to/from Byte Array in C#

By | 6 May 2003 | Article
Provides and demonstrates a hexadecimal string encoding/decoding class

Sample Image

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:

// byte newByte = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);

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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

neilck



Canada Canada

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 2 PinmemberHaiSonTran19:25 12 Apr '11  
GeneralGreat job Pinmembermapelo6316:23 29 Jan '10  
GeneralExplanation on "D3" PinmemberjenniBrooklyn23:35 13 Dec '09  
GeneralRe: Explanation on "D3" PinmemberRascalRobot8:20 27 Jan '10  
GeneralLicense Pinmembercesarfricks9:07 20 Aug '09  
Questioncan some one send me the built executable? I am not able to build it :( Pinmembervikrampatwardhan19:08 26 Jan '09  
GeneralFaster GetBytes() [modified] PinmemberMark Jerde11:16 22 Jan '09  
GeneralRe: Faster GetBytes() PinmemberMember 334182318:20 11 Oct '09  
GeneralReally good Pinmemberankit_vyas15:50 2 Sep '08  
QuestionHow can I convert null to byte array? PinmemberNadya_Nos9:06 6 Aug '08  
QuestionWhat about the speed and simplicity of my function ? [modified] Pinmembergaby_la_star1:05 12 Nov '07  
Generalthank u so much neilck ! Pinmemberbeginner_csharper1:25 15 Oct '07  
GeneralBitConverter PinmemberMihail Stefanov13:27 7 Jul '07  
GeneralSimpler, faster, better ... and most of all standard way PinmemberSébastien Ros5:36 14 May '07  
GeneralRe: Simpler, faster, better ... and most of all standard way PinmemberStefan Gheorghe13:23 3 Jul '07  
GeneralRe: Simpler, faster, better ... and most of all standard way PinmemberSebastien Ros0:31 11 Jul '07  
GeneralRe: Simpler, faster, better ... and most of all standard way [modified] PinPopularmemberGeorge Helyar6:33 5 Apr '08  
GeneralRe: Simpler, faster, better ... and most of all standard way Pinmemberj@mars4:44 16 Apr '08  
GeneralRe: Simpler, faster, better ... and most of all standard way PinmemberGeorge Helyar5:33 16 Apr '08  
GeneralRe: Simpler, faster, better ... and most of all standard way Pinmemberj@mars6:20 16 Apr '08  
GeneralRe: Simpler, faster, better ... and most of all standard way PinmemberGeorge Helyar7:43 16 Apr '08  
I have never seen it stored in the format FF-FF or 0xFF-0xFF as this is just a waste of space. For example most databases will represent their blobs as 0xFFFF when human readability is desired, text (hex, rather than base64 obviously) representation of things like hashes is always in the format 0xFFFF or just FFFF, etc. An example of this is the format of an MD5sum file such as this one.
 
It is standard for the number of characters to be twice the number of bytes but my snippet also pads the first or last byte with a 0 if this is not the case, for example "fff" can be padded to "0fff" or "ff0f" and then treated normally. (The endianness of the data specifies whether "fff" should be treated as 15,255 or 255,15 but you cannot tell this just from the string)
 
My snippet also already uses the same number of iterations in the for loop as the snippet you have just posted. It just creates a byte array half the length of the string and loops for each of those bytes incrementing by 1, multiplying by 2 to get the string offset rather than dividing by 2 to get the index offset and incrementing by 2. Essentially I am doing "for each byte in the destination array" and you are doing "for each pair of characters in the source string" Smile | :) . In days of old, this would have been a better way of doing it (* rather than /, ++ rather than += 2 etc) but I suspect that modern compilers and modern machines mean that the difference in performance is negligible, particularly on a managed environment. Regardless, I think that it is slightly more readable and any performance benefit that doesn't reduce readability is always a bonus.
 
As you have shown, you can pass a string in the format FF-FF or even 0xFF-0xFF into my method anyway simply by replacing the - or "0x" with String.Empty. The only problem with this is that F-FF should clearly be treated as 0FFF while FF-F should clearly be treated as FF0F, so any implied endianness is lost when the -s are removed. Obviously not a problem if it is FF-0F in the first place. Ideally, if you know in advance that the string is in the format FF-FF, your code that splits on '-' is better. In all other cases, it is not usable.
 
The point really is that there are many ways of doing this that are better than the code in the article.
GeneralRe: Simpler, faster, better ... and most of all standard way Pinmemberramaluciano9:12 30 Nov '08  
GeneralRe: Simpler, faster, better ... and most of all standard way Pinmemberbobslayer5:20 31 Jul '07  
GeneralPerfect PinmemberDavepow169:21 5 Mar '07  
NewsAnother fast variant of mine.... [modified] PinmemberRealFractalizeR9:32 4 Mar '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120529.1 | Last Updated 7 May 2003
Article Copyright 2003 by neilck
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid