Patrick
Patrick

Reputation: 4387

How to declare an unsigned 32-bit integer?

Is there a way to declare a 32-bit unsigned integer in PowerShell?

I'm trying to add an unsigned (begin with 0xf) i.e. 0xff000000 + 0xAA, but it turned out to be a negative number whereas I want it to be 0xff0000AA.

Upvotes: 14

Views: 18062

Answers (5)

js2010
js2010

Reputation: 27546

Another workaround, if you don't know the number in advance. Registry dwords will already be int32 or uint32.

$int = 0xff000000
$uint = [uint32]('0x{0:x}' -f $int)
$uint + 0xaa | % tostring x

ff0000aa


$uint + 0xaa | % gettype

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     UInt32                                   System.ValueType

Upvotes: 0

phuclv
phuclv

Reputation: 41962

The simplest way is to cast to [uint32] from a long literal (with the L suffix). You don't need to do the math in [uint64] or cast from a string

[uint32]0xff000000L + 0xAA

In PowerShell 6.2 a series of new suffixes have been added including a u suffix fof uint32 so this can be done even simpler

0xff000000u + 0xAA

Upvotes: 2

Pencho Ilchev
Pencho Ilchev

Reputation: 3241

The code from the currently accepted answer causes the following error on my system:

error message

This is because PowerShell always tries to convert hex values to int first so even if you cast to uint64, the environment will complain if the number has a negative int value. You can see this from the following example:

PS C:\> [uint64] (-1)
Cannot convert value "-1" to type "System.UInt64". Error: "Value was either too large or too small for a UInt64."
At line:1 char:26
+ Invoke-Expression $ENUS; [uint64] (-1)
+                          ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastIConvertible

You need to cast the string representation of the number to uint64 to avoid this:

[uint64]"0xff000000" + [uint64]"0xAA"

Upvotes: 16

Bacon Bits
Bacon Bits

Reputation: 32220

I'm assuming you meant 0xff0000AA since, as others have mentioned, 0xff00000AA is an overflow.

The easiest way to do this is to convert the value from a string. You can either use System.Convert:

[System.Convert]::ToUInt32('0xff0000AA',16)
[System.Convert]::ToUInt32('ff0000AA',16)

Or just try to cast the string, but in this case you need to prepend the 0x:

[uint32]'0xff0000AA'

If, on the other hand, you really did want to know the 32-bit unsigned integer portion of the 64-bit number `0xff00000aa', then you could do this:

[System.Convert]::ToUInt32([System.Convert]::ToString(0xff00000AA -band ([uint32]::MaxValue),16),16)

Upvotes: 0

Shay Levy
Shay Levy

Reputation: 126902

0xff00000AA is too large for a 32 bit unsigned integer, use uint64

PS> [uint64]0xff00000AA
68451041450

Upvotes: 9

Related Questions