Click here to Skip to main content
6,596,602 members and growing! (23,144 online)
Email Password   helpLost your password?
General Programming » Algorithms & Recipes » Data Structures     Intermediate

Converting Hexadecimal String to/from Byte Array in C#

By neilck

Provides and demonstrates a hexadecimal string encoding/decoding class
C#, Windows, .NET 1.0, Visual Studio, Dev
Posted:6 May 2003
Views:458,412
Bookmarked:78 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
69 votes for this article.
Popularity: 8.27 Rating: 4.50 out of 5
4 votes, 5.8%
1
2 votes, 2.9%
2
2 votes, 2.9%
3
11 votes, 15.9%
4
50 votes, 72.5%
5

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


Member

Location: Canada Canada

Other popular Algorithms & Recipes articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 62 (Total in Forum: 62) (Refresh)FirstPrevNext
GeneralLicense Pinmembercesarfricks10:07 20 Aug '09  
GeneralFastest way from string to byte[] Pinmemberveki-peki6:39 9 Apr '09  
Generalcan some one send me the built executable? I am not able to build it :( Pinmembervikrampatwardhan20:08 26 Jan '09  
GeneralFaster GetBytes() [modified] PinmemberMark Jerde12:16 22 Jan '09  
GeneralRe: Faster GetBytes() PinmemberMember 334182319:20 11 Oct '09  
GeneralReally good Pinmemberankit_vyas16:50 2 Sep '08  
GeneralHow can I convert null to byte array? PinmemberNadya_Nos10:06 6 Aug '08  
GeneralWhat about the speed and simplicity of my function ? [modified] Pinmembergaby_la_star2:05 12 Nov '07  
Generalthank u so much neilck ! Pinmemberbeginner_csharper2:25 15 Oct '07  
GeneralBitConverter PinmemberMihail Stefanov14:27 7 Jul '07  
GeneralSimpler, faster, better ... and most of all standard way PinmemberSébastien Ros6:36 14 May '07  
GeneralRe: Simpler, faster, better ... and most of all standard way PinmemberStefan Gheorghe14:23 3 Jul '07  
GeneralRe: Simpler, faster, better ... and most of all standard way PinmemberSebastien Ros1:31 11 Jul '07  
GeneralRe: Simpler, faster, better ... and most of all standard way [modified] PinmemberGeorge Helyar7:33 5 Apr '08  
GeneralRe: Simpler, faster, better ... and most of all standard way Pinmemberj@mars5:44 16 Apr '08  
GeneralRe: Simpler, faster, better ... and most of all standard way PinmemberGeorge Helyar6:33 16 Apr '08  
GeneralRe: Simpler, faster, better ... and most of all standard way Pinmemberj@mars7:20 16 Apr '08  
GeneralRe: Simpler, faster, better ... and most of all standard way PinmemberGeorge Helyar8:43 16 Apr '08  
GeneralRe: Simpler, faster, better ... and most of all standard way Pinmemberramaluciano10:12 30 Nov '08  
GeneralRe: Simpler, faster, better ... and most of all standard way Pinmemberbobslayer6:20 31 Jul '07  
GeneralPerfect PinmemberDavepow1610:21 5 Mar '07  
NewsAnother fast variant of mine.... [modified] PinmemberRealFractalizeR10:32 4 Mar '07  
GeneralI think this is faster (tested) Pinmembermeraklideve4:40 25 Jun '08  
GeneralRe: I think this is faster (tested) PinmemberRealFractalizeR12:52 25 Jun '08  
Generalbig endian hex Pinmembervadivelkumar0:28 22 Feb '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 6 May 2003
Editor: Nishant Sivakumar
Copyright 2003 by neilck
Everything else Copyright © CodeProject, 1999-2009
Web16 | Advertise on the Code Project