Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert hex string into decimal value

I tried to convert an hex string into a decimal value but it doesn't gave me the expected result

I tried convert.toint32(hexa,16) , convert.todecimal(hexa) .

I have a string look like this :

  • 1 12 94 201 198

And I convert it into :

  • 10C5EC9C6

And I know that the result is:

  • 4502505926

I need your help

Thank you very much for your help :)

like image 723
Clément Fayard Avatar asked Dec 08 '14 16:12

Clément Fayard


People also ask

How do you convert hex to decimal?

The conversion of hexadecimal to decimal is done by using the base number 16. The hexadecimal digit is expanded to multiply each digit with the power of 16. The power starts at 0 from the right moving forward towards the right with the increase in power. For the conversion to complete, the multiplied numbers are added.

What is FFFF hex in decimal?

The maximum 4-digit hexadecimal number is FFFF16 which is equal to 65,535 in decimal and so on as the number of digits increase.

How can I convert a hex string to an integer value?

To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.

What is the decimal value of hex?

The numbers in a hex are the same as decimal numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. The big difference between a hex and a decimal is that a hex also contains letters. These letters are: A, B, C, D, E, F. A hex number can be represented using a subscript of 16 (i.e. 23516).


1 Answers

The System.Decimal (C# decimal) type is a floating point type and does not allow the NumberStyles.HexNumber specifier. The range of allowed values of the System.Int32 (C# int) type is not large enough for your conversion. But you can perform this conversion with the System.Int64 (C# long) type:

string s = "10C5EC9C6";
long n = Int64.Parse(s, System.Globalization.NumberStyles.HexNumber);
'n ==> 4502505926

Of course you can convert the result to a decimal afterwards:

decimal d = (decimal)Int64.Parse(s, System.Globalization.NumberStyles.HexNumber);

Or you can directly convert the original string with decimal coded hex groups and save you the conversion to the intermediate representation as a hex string.

string s = "1 12 94 201 198";
string[] groups = s.Split();
long result = 0;
foreach (string hexGroup in groups) {
    result = 256 * result + Int32.Parse(hexGroup);
}
Console.WriteLine(result); // ==> 4502505926

Because a group represents 2 hex digits, we multiply with 16 * 16 = 256.

like image 78
Olivier Jacot-Descombes Avatar answered Oct 07 '22 04:10

Olivier Jacot-Descombes