Home > Software engineering >  Convert 4 byte array to float
Convert 4 byte array to float

Time:07-23

I have a 4 byte array I need to convert into a float. The python code to convert the array looks like this:

import struct
import codecs

byteArray = [125, 29, 2, 64]
hexfloat = ''.join(format(x, '02x') for x in byteArray)
print(struct.unpack('<f', codecs.decode(hexfloat, 'hex_codec'))[0])

Should return this: 2.0330498218536377

Do you know the dart code equivalent?

CodePudding user response:

Usually all utilities needed to work with bytes in dart can be found at dart:typed_data. The following code would be equivalent to the python one.

import 'dart:typed_data';

void main() {
  final data = [125, 29, 2, 64];
  final bytes = Uint8List.fromList(data);
  final byteData = ByteData.sublistView(bytes);
  double value = byteData.getFloat32(0,Endian.little);
  print(value); // 2.0330498218536377
}
  • Related