Parsing integer bit-patterns as IEEE 754 floats in dart
Asked Answered
M

1

3

I am getting 4 bytes of data through an interface(Bluetooth, List). The data is representing IEEE 754 float (e.g. 0x3fd0a3d7, which represents approximately 1.63 as a binary32 float)

Is there a way in dart lang to convert / type-pun this to float and then double? Something like intBitsToFloat in Java. Couldn't find anything. Or do I just have to write the IEEE 754 parsing myself?

Menhaden answered 26/3, 2019 at 10:58 Comment(0)
S
7

This is working, just import the dart:typed_data library:

  var bdata = ByteData(4);
  bdata.setInt32(0, 0x3fd0a3d7);
  print(bdata.getFloat32(0)); //Prints: 1.6299999952316284

(I'm not sure this is the most reliable way)

Storage answered 26/3, 2019 at 11:44 Comment(2)
I think it is currently the most reliable way to convert between the representtions of integers and floats: To store the representation of one into bytes and read it back as the other.Marmoreal
Nice, thanks. Can't believe I didn't find this after one hour of googling.Menhaden

© 2022 - 2024 — McMap. All rights reserved.