Main FAQ Category: C# (9)
Also in: Beginner (36) 

How to Convert Hexadecimal values To/From Integers in C# and .NET?
Posted: 24-Mar-2008
Updated: 23-May-2008
Views: 964
Here are some simple functions that show how to convert HEX string values into various C# numeric data types (and vice versa):


using System.Globalization;
 
long hextolong(string hexValue)
{
return long.Parse(hexValue, NumberStyles.AllowHexSpecifier);
}

int hextoint(string hexValue)
{
return int.Parse(hexValue, NumberStyles.AllowHexSpecifier);
}

string inttohex( int intValue )
{
return intValue.ToString("X");
}

string longtohex( long longValue )
{
return longValue.ToString("X");
}

If you need zero padding for your HEX values you can use this notation:

To produce 2 character zero padding (like 01 or 0A) use:

string inttohex( int intValue )
{
return intValue.ToString("X2");
}

To produce 4 characters zero padding (like 00A1 or 0A04) use:

string inttohex( int intValue )
{
return intValue.ToString("X4");
}