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

问题描述 投票:2回答:1

如何将big-endian十六进制变量= '0x41fe89de'转换为[single](float32)变量?

结果必须为31,8173179626465

我只知道[double] "0x41fe89de"的方式,得到结果1107200478

arrays powershell hex endianness
1个回答
3
投票
# 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之类的表达式来确定所需的字节数。
© www.soinside.com 2019 - 2024. All rights reserved.