Reputation: 348
How to convert hexadecimal string to number in C#?
I tried as below but it is giving negative value:
var dec1 = long.Parse("F0A6AFE69D2271E7", System.Globalization.NumberStyles.HexNumber);
// Result: dec1 = -1106003253459258905
While in Javascript it works fine as below:
var dec2 = parseInt("F0A6AFE69D2271E7", 16);
// Result: dec2 = 17340740820250292000
Upvotes: 1
Views: 339
Reputation: 268
See https://en.wikipedia.org/wiki/Two%27s_complement to understand why your number was interpreted as negative number. Presicely speaking, it's not "out of range" problem but, just your hex representation gives exact negative number. "long" type is signed integer and cannot hold full-64bit positive number since its MSB is kept for presenting negative numbers. Try using "ulong" instead.
Upvotes: 3
Reputation: 1503439
The number you're parsing is outside the range of long
- long.MaxValue
is 0x7FFFFFFFFFFFFFFF, and your value is 0xF0A6AFE69D2271E7.
Use ulong.Parse
instead and it should be fine.
I suspect it's "working" in JavaScript because (at the time of writing) all JavaScript numbers are 64-bit floating point values, so have a huge range - but less precision, which is why a value which is clearly odd (last hex digit 7) is giving an even result.
Upvotes: 8