How to declare an unsigned 32-bit integer?
Solution 1
0xff00000AA is too large for a 32 bit unsigned integer, use uint64
PS> [uint64]0xff00000AA
68451041450
Solution 2
The code from the currently accepted answer causes the following error on my system:
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"
Solution 3
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
Related videos on Youtube
Patrick
Updated on June 18, 2022Comments
-
Patrick almost 2 years
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 be0xff0000AA
. -
SpellingD about 12 yearsI do not get the error you described, and the answer @Shay gave works just fine for me. Using 64bit PSv2. However, just entering
0xff00000AA
does auto-convert to68451041450
without the need for casting. -
Emperor XLII almost 12 years@SpellingD: The difference is Pencho used
0xFF0000AA
(four zeros) to get a signedInt32
negative value (which fails to convert to an unsigned value), where the question uses0xFF00000AA
(five zeros) to get a signedInt64
positive value (which converts successfully). -
Bob Reynolds about 11 yearsThis does not answer the question actually asked, i.e., how to declare an unsigned 32-bit integer, with the remainder of the text implying the high bit is set. The answer provided by Pencho does provide a means to do this. Given the question asked, it seems reasonable to assume the example provided just has more hex digits than intended and not that it is "too large" for a 32 bit integer (signed or otherwise).
-
jpmc26 almost 8 yearsDo not use images to post code or errors. Copy them into the answer.
-
phuclv about 4 years
0xff000000 + 0xAA = 0xff0000AA
, not0xff00000AA
. All of them fit in uint32