3

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.

1
  • Where is the hex var from? Commented Mar 4, 2020 at 14:59

1 Answer 1

4
# 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.
Sign up to request clarification or add additional context in comments.

1 Comment

The snmp code is here. I basically turned the endian bytes into an integer by hand. stackoverflow.com/questions/27054622/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.