Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate bytes in Dart

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?
like image 473
William Avatar asked Aug 21 '14 22:08

William


1 Answers

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.

like image 116
Argenti Apparatus Avatar answered Sep 20 '22 06:09

Argenti Apparatus