Convert double to bytes

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");
  showArray(d1);
  // Get byte array from double array
  byte[] b = convertDoubleToByteArray(d1);
  // Restore double array
  double[] d2 = convertByteToDoubleArray(b);
  println("Array restored from byte array");
  showArray(d2);
}

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

byte[] convertDoubleToByteArray(double[] doubles) {
  ByteBuffer bb = ByteBuffer.allocate(doubles.length * 8);
  for (double d : doubles) {
    bb.putDouble(d);
  }
  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;
}
3 Likes