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 :)
The conversion of hexadecimal to decimal is done by using the base number 16. The hexadecimal digit is expanded to multiply each digit with the power of 16. The power starts at 0 from the right moving forward towards the right with the increase in power. For the conversion to complete, the multiplied numbers are added.
The maximum 4-digit hexadecimal number is FFFF16 which is equal to 65,535 in decimal and so on as the number of digits increase.
To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.
The numbers in a hex are the same as decimal numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. The big difference between a hex and a decimal is that a hex also contains letters. These letters are: A, B, C, D, E, F. A hex number can be represented using a subscript of 16 (i.e. 23516).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With