Click here to Skip to main content
12,622,652 members (28,393 online)
Click here to Skip to main content
Add your own
alternative version

Stats

1.5M views
12.3K downloads
100 bookmarked
Posted

Converting Hexadecimal String to/from Byte Array in C#

, 6 May 2003
Rate this:
Please Sign up or sign in to vote.
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

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralJust what I needed Pin
Joe Pardue16-Jun-05 6:05
memberJoe Pardue16-Jun-05 6:05 
GeneralGreatly Appreciated! Pin
Devon Knight13-Apr-05 14:58
memberDevon Knight13-Apr-05 14:58 
GeneralFastest I found.. Pin
stotti_no121-Mar-05 22:05
memberstotti_no121-Mar-05 22:05 
AnswerRe: Fastest I found.. Pin
tomstrummer28-Jul-07 8:07
membertomstrummer28-Jul-07 8:07 
Generalincrease speed Pin
CyberDEF3-Feb-05 12:02
memberCyberDEF3-Feb-05 12:02 
Generalthanks a lot Pin
wilson_o23-Jan-05 17:46
susswilson_o23-Jan-05 17:46 
Generalabout discarded Pin
yzh_x9-Jan-05 17:42
memberyzh_x9-Jan-05 17:42 
GeneralThanks yeah :) Pin
chuawenching9-Sep-04 17:17
memberchuawenching9-Sep-04 17:17 
This articles had saves my time of coding the hex to bytes. Thanks again Smile | :) I love the stringbuilder part...
GeneralImprove performance Pin
Esteves15-Nov-03 18:05
memberEsteves15-Nov-03 18:05 
GeneralVery good Pin
mikeperetz5-Sep-03 12:11
membermikeperetz5-Sep-03 12:11 
GeneralRe: Very good Pin
bobseadream9-May-04 6:58
memberbobseadream9-May-04 6:58 
GeneralPerformance improvement Pin
Patrik Reali3-Jul-03 6:37
memberPatrik Reali3-Jul-03 6:37 
GeneralRe: Performance improvement Pin
neilck3-Jul-03 7:59
memberneilck3-Jul-03 7:59 
GeneralRe: Performance improvement Pin
Volker von Einem6-Feb-07 4:34
memberVolker von Einem6-Feb-07 4:34 
GeneralThanks Pin
jmandile24-Jun-03 16:26
memberjmandile24-Jun-03 16:26 
GeneralAnother way Pin
Phillip Vetter13-May-03 1:31
memberPhillip Vetter13-May-03 1:31 
GeneralRe: Another way Pin
slick_bytes27-Nov-03 19:57
memberslick_bytes27-Nov-03 19:57 
GeneralRe: Another way using array of bytes Pin
Larry102425-Feb-04 6:05
memberLarry102425-Feb-04 6:05 
GeneralRe: Another way Pin
DarkStarPL12-Feb-07 23:49
memberDarkStarPL12-Feb-07 23:49 
GeneralYou can use System.Text.Encoding.ASCII.* too... Pin
Jhon12-May-03 21:19
memberJhon12-May-03 21:19 
GeneralRe: You can use System.Text.Encoding.ASCII.* too... Pin
yizumi2-Dec-04 15:30
memberyizumi2-Dec-04 15:30 
GeneralCoincidentally, I wrote the same function a week ago Pin
crowdozer8-May-03 9:01
membercrowdozer8-May-03 9:01 
GeneralRe: Coincidentally, I wrote the same function a week ago Pin
neilck9-May-03 5:57
memberneilck9-May-03 5:57 
GeneralRe: Coincidentally, I wrote the same function a week ago Pin
Anonymous19-Mar-04 20:40
sussAnonymous19-Mar-04 20:40 
GeneralVery nice Pin
Marcin7-May-03 11:35
memberMarcin7-May-03 11:35 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161128.1 | Last Updated 7 May 2003
Article Copyright 2003 by neilck
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid