# Float value to Byte array

Hello there how to convert float val to byte array ? i have this function that work in oposite way, it converts Byte array to Float value:

``````public float byteArrayToFloat(byte test[]) {
int bits = 0;
int i = 3;
for (int shifter = 3; shifter >= 0; shifter--) {
bits |= ((int) test[i] & MASK) << (shifter * 8);
i--;
}
println(bits);
return Float.intBitsToFloat(bits);
}
``````

So… How to make floatToByteArray function?

A search for " floatToByteArray" is a good start.

I did this a while back and was able to come up with solutions. This is my take on it for both opposite conversion ways. You can also take a look at this site below in order to double-check results: ``````/**
* 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 << 030 | i << 020 | i << 010 | i);
}
``````
2 Likes

Why is there @SafeVarargs ?

And difference between “>>” and “>>>” ?

… And why is the shifts written as “030”, “020” and “010” ? Maybe iam not the only one who wants to know ahh whe you place zero “0” before number, it is in the octal number system, thats it 1 Like

Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/SafeVarargs.html

Bit-shift operator `>>>` shifts the most significant bit (negative bit), so the value isn’t negative anymore.

`println(030, 020, 010); // 24, 16, 8 (Octal)`

1 Like