Click here to Skip to main content
15,881,413 members
Articles / Programming Languages / C#
Article

Converting Hexadecimal String to/from Byte Array in C#

Rate me:
Please Sign up or sign in to vote.
4.71/5 (78 votes)
6 May 20032 min read 896.4K   14.4K   103   67
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:

C#
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:

C#
// 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


Written By
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseThank you Pin
Member 1382429512-May-18 14:35
Member 1382429512-May-18 14:35 
QuestionThank you! Pin
smirson24-May-17 2:15
smirson24-May-17 2:15 
GeneralMy vote of 2 Pin
HaiSonTran12-Apr-11 19:25
HaiSonTran12-Apr-11 19:25 
I USED Abyte=CTYPE("&H"&Str.substring(i,2),byte)
return byte value for 2 hex char and Hex(Abyte)to string hex.
GeneralGreat job Pin
mapelo6329-Jan-10 16:23
mapelo6329-Jan-10 16:23 
GeneralExplanation on "D3" Pin
jenniBrooklyn13-Dec-09 23:35
jenniBrooklyn13-Dec-09 23:35 
GeneralRe: Explanation on "D3" Pin
EddieRich27-Jan-10 8:20
EddieRich27-Jan-10 8:20 
GeneralLicense Pin
cesarfricks20-Aug-09 9:07
cesarfricks20-Aug-09 9:07 
Questioncan some one send me the built executable? I am not able to build it :( Pin
vikrampatwardhan26-Jan-09 19:08
vikrampatwardhan26-Jan-09 19:08 
GeneralFaster GetBytes() [modified] Pin
Mark Jerde22-Jan-09 11:16
Mark Jerde22-Jan-09 11:16 
GeneralRe: Faster GetBytes() Pin
Dragon Chuang11-Oct-09 18:20
Dragon Chuang11-Oct-09 18:20 
GeneralReally good Pin
ankit_vyas2-Sep-08 15:50
ankit_vyas2-Sep-08 15:50 
QuestionHow can I convert null to byte array? Pin
Naomi_N6-Aug-08 9:06
Naomi_N6-Aug-08 9:06 
QuestionWhat about the speed and simplicity of my function ? [modified] Pin
gbrlhtclcq12-Nov-07 1:05
gbrlhtclcq12-Nov-07 1:05 
Generalthank u so much neilck ! Pin
beginner_csharper15-Oct-07 1:25
beginner_csharper15-Oct-07 1:25 
GeneralBitConverter Pin
Mihail Stefanov7-Jul-07 13:27
Mihail Stefanov7-Jul-07 13:27 
GeneralSimpler, faster, better ... and most of all standard way Pin
Sebastien Ros14-May-07 5:36
Sebastien Ros14-May-07 5:36 
GeneralRe: Simpler, faster, better ... and most of all standard way Pin
Stefan Gheorghe3-Jul-07 13:23
Stefan Gheorghe3-Jul-07 13:23 
GeneralRe: Simpler, faster, better ... and most of all standard way Pin
Sebastien Ros11-Jul-07 0:31
Sebastien Ros11-Jul-07 0:31 
GeneralRe: Simpler, faster, better ... and most of all standard way [modified] Pin
George Helyar5-Apr-08 6:33
George Helyar5-Apr-08 6:33 
GeneralRe: Simpler, faster, better ... and most of all standard way Pin
j@mars16-Apr-08 4:44
j@mars16-Apr-08 4:44 
GeneralRe: Simpler, faster, better ... and most of all standard way Pin
George Helyar16-Apr-08 5:33
George Helyar16-Apr-08 5:33 
GeneralRe: Simpler, faster, better ... and most of all standard way Pin
j@mars16-Apr-08 6:20
j@mars16-Apr-08 6:20 
GeneralRe: Simpler, faster, better ... and most of all standard way Pin
George Helyar16-Apr-08 7:43
George Helyar16-Apr-08 7:43 
GeneralRe: Simpler, faster, better ... and most of all standard way Pin
ramaluciano30-Nov-08 9:12
ramaluciano30-Nov-08 9:12 
GeneralRe: Simpler, faster, better ... and most of all standard way Pin
bobslayer31-Jul-07 5:20
bobslayer31-Jul-07 5:20 

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.