PowerShell:将十六进制变量转换为单个(float32)大端变量

PowerShell: Converting a hex variable into a single (float32) big endian variable

如何将大端十六进制变量 = '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(默认输出格式)。

  • 用于将十六进制字符串转换为字节数组的技术在 中进行了说明。

  • 字节数组到平台原生[single]实例的转换(System.Single) is performed via the System.BitConverterclass.

    • 注意传递给::ToSingle()的字节数必须与构成目标类型的字节数完全匹配;在这种情况下,需要 4 字节,因为 [single]32 位类型(4 字节乘以 8 位);如有必要和适当,提供一个用 0 字节填充的数组;使用 [System.Runtime.InteropServices.Marshal]::SizeOf([single] 0) 等表达式来确定所需的字节数。