问题描述
我尝试将十六进制字符串转换为十进制值,但没有给我预期的结果
I tried to convert an hex string into a decimal value but it doesn't gave me the expected result
我尝试了 convert.toint32 (hexa,16)
, convert.todecimal(hexa)
。
我有字符串如下所示:
- 1 12 94201198
然后将其转换为:
- 10C5EC9C6
我知道结果是:
- 4502505926
我需要您的帮助
非常感谢您的帮助:)
推荐答案
System.Decimal
(C# decimal
)类型是浮点类型,不允许 NumberStyles.HexNumber
说明符。 System.Int32
(C# int
)类型的允许值范围不足以进行转换。但是您可以使用 System.Int64
(C# long
)类型执行此转换:
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
由于组代表2个十六进制数字,因此我们乘以16 * 16 = 256。
Because a group represents 2 hex digits, we multiply with 16 * 16 = 256.
这篇关于如何将十六进制字符串转换为十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!