Clément Fayard
Clément Fayard

Reputation: 155

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 :

And I convert it into :

And I know that the result is:

I need your help

Thank you very much for your help :)

Upvotes: 11

Views: 23863

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112259

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.

Upvotes: 18

Related Questions