How to convert int to hex and hex to int in C# or VB.NET

How to convert int to hex and hex to int in C# or VB.NET?

Example C#

const int intValue = 3190174; // start int value
var resultHex = intValue.ToString("X"); // convert to Hex, result (uppercase) == 30AD9E
resultHex = intValue.ToString("x"); // convert to Hex, result (lowercase) == 30ad9e
var resultInt = int.Parse(resultHex, System.Globalization.NumberStyles.HexNumber); // convert to back to int, result == 3190174

Example VB.NET

Const  intValue As Integer = 3190174 'start int value
Dim resultHex = intValue.ToString("X") ' convert to Hex, result (uppercase) == 30AD9E
resultHex = intValue.ToString("x") ' convert to Hex, result (lowercase) == 30ad9e
Dim resultInt = Integer.Parse(resultHex, System.Globalization.NumberStyles.HexNumber) ' convert to back to int, result == 3190174

see also Standard Numeric Format Strings in the MSDN.

Please Share us:
Please rate this snippet

Leave a Reply