简体   繁体   English

如何将十六进制字符串转换为十进制值

[英]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) . 我试过convert.toint32(hexa,16)convert.todecimal(hexa)

I have a string look like this : 我有一个字符串看起来像这样:

  • 1 12 94 201 198 1 12 94 201 198

And I convert it into : 我把它转换成:

  • 10C5EC9C6 10C5EC9C6

And I know that the result is: 我知道结果是:

  • 4502505926 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. System.Decimal (C# decimal )类型是浮点类型,不允许使用NumberStyles.HexNumber说明符。 The range of allowed values of the System.Int32 (C# int ) type is not large enough for your conversion. System.Int32 (C# int )类型的允许值范围不足以进行转换。 But you can perform this conversion with the System.Int64 (C# long ) type: 但您可以使用System.Int64 (C# long )类型执行此转换:

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

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. 因为一个组代表2个十六进制数字,所以我们乘以16 * 16 = 256。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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