How to Convert Hexadecimal values To/From Integers in C# and .NET?

 Copyright © 2007-2012 www.AspDotNetFaq.com

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");
}

 Copyright © 2007-2012 www.AspDotNetFaq.com