Categories

Integer sizes

 

If you’ve used PowerShell for any time you will be away of [int] meaning integer. One common use is in functions to define a parameter’s data type

function test1 {
param (
  [int]$a,
  [int]$b
)
$a * $b
}

We can use this function

PS> test1 -a 10 -b 6
60

OK simple stuff but what if we do this

PS> test1 -a 2147483648 -b 17
test1 : Cannot process argument transformation on parameter 'a'. Cannot convert
value "2147483648" to type "System.Int32". Error: "Value was either too large
or too small for an Int32."
At line:1 char:9
+ test1 -a <<<<  2147483648 -b 17
    + CategoryInfo          : InvalidData: (:) [test1], ParameterBindin...mati
   onException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,test1

Oh

Integers come in a number of different sizes – denoted by the number of bits that are used to store the number – 16, 32 and 64 respectively.  The standard [int] is a 32bit integer (4 bytes)

We can see the maximum and minimum numbers that can be stored in these data types using the MaxValue and MinValue properties

"`n16 bit integer"
"$([int16]::MinValue) to $([int16]::MaxValue)"

"`n32 bit integer"
"$([int32]::MinValue) to $([int32]::MaxValue)"

"`n32 bit integer alternative"
"$([int]::MinValue) to $([int]::MaxValue)"

"`n64 bit integer"
"$([int64]::MinValue) to $([int64]::MaxValue)"

 

which gives these results

16 bit integer
-32768 to 32767

32 bit integer
-2147483648 to 2147483647

32 bit integer alternative
-2147483648 to 2147483647

64 bit integer
-9223372036854775808 to 9223372036854775807

 

So 2147483648 is one bigger than the maximum value storable in 32 bit integer. We could use a 64bit integer or we can use an unsigned integer. This only contains positive values

"`nunsigned 16 bit integer"
"$([uint16]::MinValue) to $([uint16]::MaxValue)"

"`nunsigned 32 bit integer"
"$([uint32]::MinValue) to $([uint32]::MaxValue)"

"`nunsigned 64 bit integer"
"$([uint64]::MinValue) to $([uint64]::MaxValue)"

 

unsigned 16 bit integer
0 to 65535

unsigned 32 bit integer
0 to 4294967295

unsigned 64 bit integer
0 to 18446744073709551615

Which should you use?  Use int64 if likely to have negative values and possibly uint32 if definitely only positive values

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>