Convert double to bytes

I need to convert a single array of doubles to 8 arrays of bytes to save…but not sure this is possible…currently I am converting to float then to str…to save as txt…but there is some loss with this…I would prefer to preserve the double precision also the savestrings function seems really sluggish and inefficient.

1 Like

i not think you need a text file???

can use the library BezierSQLib
to create a SQLite3 database file
and try save values

REAL . The value is a floating point value, stored as an 8-byte IEEE floating point number.

The following sketch will convert double>byte and byte>double arrays.
Sample output:

Original array
0.24904495375353408  0.15873060773194125  0.24651129906363822  0.2543479093984985
Array restored from byte array
0.24904495375353408  0.15873060773194125  0.24651129906363822  0.2543479093984985


import java.nio.ByteBuffer;
import java.util.Random;

void setup() {
  Random rnd = new Random();
  double[] d1 = new double[4];
  for (int i = 0; i < d1.length; i++) {
    d1[i] = rnd.nextDouble();
  println("Original array");
  // Get byte array from double array
  byte[] b = convertDoubleToByteArray(d1);
  // Restore double array
  double[] d2 = convertByteToDoubleArray(b);
  println("Array restored from byte array");

void showArray(double[] doubles) {
  for (double d : doubles) {
    print("  " + d);

byte[] convertDoubleToByteArray(double[] doubles) {
  ByteBuffer bb = ByteBuffer.allocate(doubles.length * 8);
  for (double d : doubles) {
  return bb.array();

double[] convertByteToDoubleArray(byte[] bytes) {
  ByteBuffer bb = ByteBuffer.wrap(bytes);
  double[] doubles = new double[bytes.length / 8];
  for (int i = 0; i < doubles.length; i++) {
    doubles[i] = bb.getDouble();
  return doubles;


Thank you for the responses…I will go with quarks suggestion…

I managed to do this with lots of bit shifting, masking, promoting… what a workout that was!
I like to write code as an exercise without too much influence and got it working!
Something like this:
double > Double.doubleToLongBits > byte array > Double.longBitsToDouble > double
I did a lot of this in my early years coding in assembly and C.

I am going to try this with my Arduino to Processing.
I can take those doubles and pack them into bytes and do eight serial writes!

My Arduino sends the following quaternion data as viewed on serial monitor:


Arduino Code:

void plotQuat0()
// Quaternion data
  imu::Quaternion quat = bno.getQuat();
    Serial.print(quat.w(), 14);
    Serial.print(quat.x(), 14);
    Serial.print(quat.y(), 14);
    Serial.print(quat.z(), 14);

Thanks for inspiring me to do this!


1 Like