问题描述
我的System.UInt32
类型的数字如下:4.294.967.176(以字节为单位:FFFF FF88
)。
我必须将此数字解释为system.int32
类型的数字,该数字将是:-120(以字节为单位:FFFF FF88
)。
在像C或C ++这样的语言中,简单的类型转换可以解决我的问题,但是在PowerShell中进行类型转换:
[Int32][UInt32]4294967176
引发错误:
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
PowerShell似乎试图“转换”该值,而不只是强制转换它。那么,如何将System.UInt32
强制转换为system.int32
,这意味着不更改数据,而是使用其他解释/表示形式?
解决方法
由于.Net数字数据类型支持转换为等效的十六进制,因此首先将UInt32转换为字符串。然后使用System.Convert.ToInt32()
并将十六进制解析为int。像这样
$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