Concatenate bytes in Dart
Let's say I have a list of integers in bytes. The first 4 bytes (the first 4 elements in the list) are actually the components of a single-precision floating point number. I would like to concatenate 4 bytes and convert them to float. How should I do it?
File myFile = new File('binaryfile.bin') List<int> fileBytes = myFile.readAsBytes() double myFloat = generateFloat(fileBytes.getRange(0, 4)); // how do I make this?
source to share
Use typed data arrays .
Quote from the description ByteData
:
A sequence of fixed-length, random-access bytes that also provides random and non-uniform access to fixed-width integers and floating point numbers represented by those bytes. ByteData can be used to pack and unpack data from external sources (such as networks or file systems).
Continuing with your example
import 'dart:io' import 'dart:typed_data'; ... File myFile = new File('binaryfile.bin') List<int> fileBytes = myFile.readAsBytesSync(); // Turn list of ints into a byte buffer ByteBuffer buffer = new Int8List.fromList(fileBytes).buffer; // Wrap a ByteData object around buffer ByteData byteData = new ByteData.view(buffer); // Read first 4 bytes of buffer as a floating point double x = byteData.getFloat32(0);
However, be aware of the endianness of your data.
Others can point out better ways to get data from a file into ByteBuffer
.
source to share