8

Say I have a List of byte-sized integers. The first 4 bytes (first 4 items in the list) are actually components of a single-precision floating point number. I would like to concatenate the 4 bytes and transform them into a float. How would I do this?

File myFile = new File('binaryfile.bin')
List<int> fileBytes = myFile.readAsBytes()
double myFloat = generateFloat(fileBytes.getRange(0, 4)); // how do I make this?

1 Answer 1

12

Use typed data arrays.

Quoting from the description of ByteData:

A fixed-length, random-access sequence of bytes that also provides random and unaligned access to the fixed-width integers and floating point numbers represented by those bytes. ByteData may be used to pack and unpack data from external sources (such as networks or files systems)

Continuing 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 may point out better ways of getting data from a file into a ByteBuffer.

1
  • I assume that should be a Uint8List rather than Int8List? Also an optimisation - readAsBytes() actually returns a Uint8List already. So you can prevent a copy - for example: ByteBuffer buffer = fileBytes is Uint8List ? fileBytes.buffer : new Uint8List(fileBytes).buffer;
    – Greg Lowe
    Commented Nov 23, 2014 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.