I am using a Modbus flutter lib, reading 2 registers I obtain:
[16177, 4660] I need a function to convert it to a 32 bit float value: 0.7
I found this function
ByteBuffer buffer = new Uint16List.fromList(fileBytes).buffer;
ByteData byteData = new ByteData.view(buffer);
double x = byteData.getFloat32(0);
It says 0.000045747037802357227 swap byte value
Can you help
I always find it easiest to start with the byte array and insert stuff into that. What's happening is that your code is defaulting to the native endianness (apparently little
) but you need to be doing this in big endianness.
Here's an overly verbose solution that you can cut out the print statements (and hex codec)
import 'dart:typed_data';
import 'package:convert/convert.dart'; // only needed for debugging
void main() {
final registers = [16177, 4660];
final bytes = Uint8List(4); // start with the 4 bytes = 32 bits
var byteData = bytes.buffer.asByteData(); // ByteData lets you choose the endianness
byteData.setInt16(0, registers[0], Endian.big); // Note big is the default here, but shown for completeness
byteData.setInt16(2, registers[1], Endian.big);
print(bytes); // just for debugging - does my byte order look right?
print(hex.encode(bytes)); // ditto
final f32 = byteData.getFloat32(0, Endian.big);
print(f32);
}