简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM