RonaDona
RonaDona

Reputation: 932

Hex to Decimal Conversion - PowerShell 5

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?

Upvotes: 6

Views: 19394

Answers (3)

Because I hate accelerators:

$Hex="0x18"
[System.Convert]::ToInt32($Hex,16)
24

$Hex="18"
[System.Convert]::ToInt32($Hex,16)
24

Upvotes: 0

vonPryz
vonPryz

Reputation: 24091

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.

Upvotes: 4

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200523

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"

Upvotes: 10

Related Questions