Search code examples
rakupackunpack

How to convert Hex string to IEEE754 Float number with Raku?


In Python, unpack can convert Hex string to IEEE754 Float number:

import struct

print(struct.unpack('<f', bytes.fromhex("00000042"))[0]) # 32.0

< represents LITTLE ENDIAN byte order, and f represents Float format.

How to convert Hex string to IEEE754 Float number with Raku?


Solution

  • A possible approach is:

    1. Parse it into an integer
    2. Write the integer into a Buf
    3. Read a floating point number from that Buf

    For example:

    say do given Buf.new {
        .write-int32(0, :16("00000042"), BigEndian);
        .read-num32(0)
    }
    

    Which gives the same output (32) as the Python example.