如何将大端十六进制变量 = '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.BitConverter
执行的。类。- 请注意,传递给
::ToSingle()
的字节数必须与构成目标类型的字节数完全匹配;在这种情况下,需要4
字节,因为[single]
是32
位类型(4
字节倍8
位);如有必要和适当,提供一个用0
字节填充的数组;使用诸如[System.Runtime.InteropServices.Marshal]::SizeOf([single] 0)
之类的表达式来确定所需的字节数。
- 请注意,传递给
关于arrays - PowerShell:将十六进制变量转换为单个(float32)大端变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60523514/