Click here to Skip to main content
14,664,191 members
Articles » General Programming » Algorithms & Recipes » Data Structures
Article
Posted 6 May 2003

Stats

855.4K views
14.1K downloads
103 bookmarked

Converting Hexadecimal String to/from Byte Array in C#

Rate this:
4.71 (78 votes)
Please Sign up or sign in to vote.
4.71 (78 votes)
6 May 2003
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

Share

About the Author

neilck
Canada Canada
No Biography provided

Comments and Discussions

 
GeneralI think this is faster (tested) Pin
meraklideve25-Jun-08 3:40
Membermeraklideve25-Jun-08 3:40 
GeneralRe: I think this is faster (tested) Pin
VladislavRastrusny25-Jun-08 11:52
MemberVladislavRastrusny25-Jun-08 11:52 
Generalbig endian hex Pin
vadivelkumar21-Feb-07 23:28
Membervadivelkumar21-Feb-07 23:28 
GeneralBuilt in .NET parse function that does this Pin
MGutman8-Jan-07 7:45
MemberMGutman8-Jan-07 7:45 
GeneralRe: Built in .NET parse function that does this Pin
noGuns19-Apr-07 10:43
MembernoGuns19-Apr-07 10:43 
GeneralRe: Built in .NET parse function that does this Pin
Mr Marchepane7-May-07 9:10
MemberMr Marchepane7-May-07 9:10 
GeneralRe: Built in .NET parse function that does this Pin
Simon Capewell22-Nov-07 3:29
MemberSimon Capewell22-Nov-07 3:29 
GeneralSaved me a bunch of time - thanks Pin
TimBSmith19715-Jan-07 13:36
MemberTimBSmith19715-Jan-07 13:36 
Didnt have to to do this pattern again - thanks!

Tim.Smith@Venturality.com
Generalwonderful Pin
sinan12345617-Oct-06 5:04
Membersinan12345617-Oct-06 5:04 
General'.' being not properly converted Pin
Hoodwink13-Sep-06 12:20
MemberHoodwink13-Sep-06 12:20 
GeneralSimpler Pin
raytaller6-Jun-06 6:51
Memberraytaller6-Jun-06 6:51 
GeneralRe: Simpler Pin
MGutman8-Jan-07 7:49
MemberMGutman8-Jan-07 7:49 
GeneralIT students Pin
sunset_h22_m6-Apr-06 3:23
Membersunset_h22_m6-Apr-06 3:23 
GeneralSystem.Uri.IsHexDigit Pin
Chirpychips3-Dec-05 3:06
MemberChirpychips3-Dec-05 3:06 
GeneralThanks to all for performance tips Pin
neilck22-Jun-05 14:29
Memberneilck22-Jun-05 14:29 
GeneralJust what I needed Pin
Joe Pardue16-Jun-05 5:05
MemberJoe Pardue16-Jun-05 5:05 
GeneralGreatly Appreciated! Pin
Devon Knight13-Apr-05 13:58
MemberDevon Knight13-Apr-05 13:58 
GeneralFastest I found.. Pin
Sven So.21-Mar-05 21:05
MemberSven So.21-Mar-05 21:05 
AnswerRe: Fastest I found.. Pin
tomstrummer28-Jul-07 7:07
Membertomstrummer28-Jul-07 7:07 
Generalincrease speed Pin
CyberDEF3-Feb-05 11:02
MemberCyberDEF3-Feb-05 11:02 
Generalthanks a lot Pin
wilson_o23-Jan-05 16:46
susswilson_o23-Jan-05 16:46 
Generalabout discarded Pin
yzh_x9-Jan-05 16:42
Memberyzh_x9-Jan-05 16:42 
GeneralThanks yeah :) Pin
Chua Wen Ching9-Sep-04 16:17
MemberChua Wen Ching9-Sep-04 16:17 
GeneralImprove performance Pin
Esteves15-Nov-03 17:05
MemberEsteves15-Nov-03 17:05 
GeneralVery good Pin
mikeperetz5-Sep-03 11:11
Membermikeperetz5-Sep-03 11:11 

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

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