Search code examples
arrayspowershellhexendianness

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


How can I convert a big-endian hex-variable = '0x41fe89de' into a [single] (float32) variable?

The result has to be 31,8173179626465.

I only know the way with [double] "0x41fe89de", getting the result 1107200478.


Solution

  • # 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)
    

    The above yields 31.81732 (with the default output formatting).

    • The technique used to convert the hex string to a byte array is explained in this answer.

    • The conversion of the byte array to a platform-native [single] instance (System.Single) is performed via the System.BitConverter class.

      • Note that the number of bytes passed to ::ToSingle() must be an exact match for the number of bytes that make up the target type; in this case, 4 bytes are required, because [single] is a 32-bit type (4 bytes times 8 bits); if necessary and appropriate, provide an array that is padded with 0 bytes; use an expression such as [System.Runtime.InteropServices.Marshal]::SizeOf([single] 0) to determine the required byte count.