Float value to Byte array

This is my take on it for both opposite conversion ways. :left_right_arrow:
You can also take a look at this site below in order to double-check results: :heavy_check_mark:

/**
 * Float As Bytes Array (v1.1.1)
 * GoToLoop (2019/Dec/29)
 * https://Discourse.Processing.org/t/float-value-to-byte-array/16698/3
 */

static final float MY_FLOAT = -PI;

byte[] floatBytes;
float convertedFloat;

void setup() {
  println(MY_FLOAT);

  floatBytes = floatToByteArr(MY_FLOAT);
  for (final byte b : floatBytes)  print(hex(b), TAB);
  println();

  convertedFloat = byteArrToFloat(floatBytes);
  println(convertedFloat, TAB, convertedFloat == MY_FLOAT);

  exit();
}

static final byte[] floatToByteArr(final float f) {
  return byte(floatToIntArr(f));
}

static final int[] floatToIntArr(final float f) {
  final int i = Float.floatToIntBits(f);
  return new int[] { i >>> 030, i >> 020 & 0xff, i >> 010 & 0xff, i & 0xff };
}

@SafeVarargs static final float byteArrToFloat(final byte... b) {
  return b != null? intArrToFloat(int(b)) : MIN_FLOAT;
}

@SafeVarargs static final float intArrToFloat(final int... i) {
  if (i == null || i.length < Float.BYTES)  return MIN_FLOAT;
  return Float.intBitsToFloat(i[0] << 030 | i[1] << 020 | i[2] << 010 | i[3]);
}
3 Likes