How to declare a 32-bit unsigned integer?

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

I am trying to add unsigned (starting with 0xf ), i.e. 0xff000000 + 0xAA , but it turned out to be negative, whereas I want it to be 0xff00000AA .

+4
source share
3 answers

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

 PS> [uint64]0xff00000AA 68451041450 
+5
source

The code from the currently accepted answer causes the following error on my system: enter image description here

This is because Powershell always first tries to convert hexadecimal values ​​to int, 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" 
+10
source

I assume you meant 0xff0000AA , as others have pointed out, 0xff00000AA is an overflow.

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

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

Or just try specifying a string, but in this case you need to add 0x :

 [uint32]'0xff0000AA' 

If, on the other hand, you really wanted to know the 32-bit unsigned integer part of the 64-bit number "0xff00000aa", you could do this:

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

Source: https://habr.com/ru/post/1412861/


All Articles