11

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 :)

0

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.