# Convert double to bytes

**URL:** https://discourse.processing.org/t/convert-double-to-bytes/12154
**Category:** Coding Questions
**Created:** [June 18, 2019, 2:17pm UTC](https://discourse.processing.org/t/convert-double-to-bytes/12154 "2019-06-18T14:17:32Z")
**Posts on this page:** 1
**Showing post:** 3

<div class="post-metadata">

### Author: ![quark](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/quark/32/26_2.png) [@quark](https://discourse.processing.org/u/quark)
#### Post date: [June 19, 2019, 9:56am UTC](https://discourse.processing.org/t/convert-double-to-bytes/12154/3 "2019-06-19T09:56:34Z")

</div>

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

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

```

.

```auto
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;
}

```

---

_[View the full topic](https://discourse.processing.org/t/convert-double-to-bytes/12154)._
