I have the following number of type System.UInt32
: 4.294.967.176 (in bytes: FFFF FF88
).
I have to interpret this number as a number of type System.Int32
, where it will be: -120 (in bytes still: FFFF FF88
).
In languages like C or C++ a simple type cast would solve my problem, but type casting in PowerShell:
[Int32][UInt32]4294967176
throws an error:
Cannot convert value "4294967176" to type "System.Int32". Error: "Value was either too large or too small for an
Int32."
At line:1 char:1
+ [Int32][UInt32]4294967176
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastIConvertible
It looks like PowerShell is trying to "convert" the value instead of just casting it. So, how do I cast System.UInt32
to System.Int32
, meaning not changing the data, but using another interpretation/representation?
Since .Net numeric data types support conversion into hex equivalents, convert the UInt32 into string first. Then use System.Convert.ToInt32()
and parse hex to int. Like so,
$u = [UInt32]4294967176
$u.tostring('x')
ffffff88
# Convert hex based value to int
$i = [convert]::toint32($u.tostring('x'), 16)
# Check that type is int32
$i.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
# Value
$i
-120