Hex to Decimal Conversion - PowerShell 5

爱⌒轻易说出口 提交于 2020-12-12 07:43:27

问题


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?


回答1:


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"



回答2:


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.



来源:https://stackoverflow.com/questions/38567479/hex-to-decimal-conversion-powershell-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!