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 MASK = 0xff;
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?
glv
2
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[0] << 030 | i[1] << 020 | i[2] << 010 | i[3]);
}
3 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
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)
2 Likes