How to convert Hex string to IEEE754 Float number with Raku?
Asked Answered
I

1

9

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?

Intelligible answered 14/7, 2023 at 11:3 Comment(3)
I'm not really sure what the conversion is supposed to do, what does the string "00000042" represent? A hexadecimal number as a string? Or a list of bytes 00 00 00 42? And what is the number 32.0? If you enter "00000052" in your Python code above you get 137438953472.0, is that intended?Commonly
Anyway, in Raku you might be after something like say "00000042".encode>>.base(16)[*-1].Rat.raku.Commonly
@Commonly 00000042 is a list of bytes: 00 00 00 42Intelligible
E
8

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.

Expulsion answered 14/7, 2023 at 15:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.