For some reason, when converting some values in PowerShell from Hex to Decimal, I get incorrect value.
For example:
- Type 0xC0000000 then hit enter, you'll get -1073741824 which is incorrect, the right value is 3221225472. The answer given is the value for the negative Hex number I entered FFFFFFFFC0000000
I thought this could be an interpretation issue so I explicitly asked to convert the value to from Hex to Base10 (Decimal), I still got the same incorrect answer -1073741824:
[Convert]::ToString(0xc0000000,10)
Why does PowerShell interpret 0xc0000000 as the negative for the Hex number c0000000? am I missing something here?
That's a PowerShell gotcha (exists in earlier versions too). The value is interpreted as a signed integer when you actually want it to be an unsigned integer. You need to do the conversion like this to get around the issue:
[uint32]"0xC0000000"
Ansgar already provided the work-around, but some explanation about what's going on might be of interest.
The root cause for this phenomenon is caused by the binary system. It doesn't really have a concept of negative numbers. There are just bits: series of ones and zeros. In order to interpret a number as either positive or negative, creative trickery has been invented.
What happens in your case is that 0xC <=> 12dec <=> 1100 bin. Thus, as the first bit is one, the bit pattern is interpreted as negative value and you get -1073741824 as the result. This, by the way, is the reason why some Windows' error messages contain nonsensical negative error codes.
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