toBinary method

ByteData toBinary({
  1. bool jsonFormat = false,
})

Exporting to binary jsonFormat (optional): Set to true to use JSON string format, false to use binary format (default: false)

Expected output: bd1 and bd2 will be ByteData objects containing the matrix data in the chosen format

Example:

ByteData bd1 = matrix.toBinary(jsonFormat: false); // Binary format
ByteData bd2 = matrix.toBinary(jsonFormat: true); // JSON format

Implementation

ByteData toBinary({bool jsonFormat = false}) {
  if (jsonFormat) {
    String jsonString = toJSON();
    return ByteData.view(utf8.encoder.convert(jsonString).buffer);
  } else {
    int numRows = rowCount;
    int numCols = columnCount;
    int bufferSize = 8 + numRows * numCols * 8;
    ByteData byteData = ByteData(bufferSize);

    byteData.setInt32(0, numRows, Endian.little);
    byteData.setInt32(4, numCols, Endian.little);
    int offset = 8;

    for (int i = 0; i < numRows; i++) {
      for (int j = 0; j < numCols; j++) {
        byteData.setFloat64(offset, this[i][j], Endian.little);
        offset += 8;
      }
    }
    return byteData;
  }
}