如何将big-endian十六进制变量= '0x41fe89de'
转换为[single]
(float32)变量?
结果必须为31,8173179626465
。
我只知道[double] "0x41fe89de"
的方式,得到结果1107200478
。
# Input: a string representing a number or big-endian byte sequence
# in hexadecimal form.
$hex = '0x41fe89de'
# Convert the hex input string to a byte array.
$byteArray = [byte[]] ($hex -replace '^0x' -split '(..)' -ne '' -replace '^', '0x')
# Convert from big-endian to little-endian, if necessary, by
# reversing the order of the bytes to match the platform's.
if ([BitConverter]::IsLittleEndian) {
[Array]::Reverse($byteArray)
}
# Convert to a platform-native [single] instance.
[BitConverter]::ToSingle($byteArray, 0)
以上产生31.81732
(具有默认的输出格式)。>>
用于将十六进制字符串转换为字节数组的技术在this answer中进行了说明。
字节数组到平台本地[single]
实例(System.Single
)的转换是通过System.Single
类执行的。
System.BitConverter
的字节数必须与构成目标类型的字节数完全匹配;在这种情况下,由于System.BitConverter
是::ToSingle()
位类型(4
字节乘以[single]
位),因此需要32
字节。如有必要,请提供一个填充有4
字节的数组;使用诸如8
之类的表达式来确定所需的字节数。