So what I'm trying to do here is get a float[]
, convert it to byte[]
, send it through the network as a datagram packet and then convert it back to a byte[]
at the receiving terminal.
Now I know I can convert float[]
to byte[]
by using the getBytes[]
method. But I don't know how to reverse the conversion.
An improvement to Steven Chou's answer
final static int BYTES_IN_FLOAT = Float.SIZE / Byte.SIZE;
public static byte[] toByteArray(float[] floatArray) {
ByteBuffer buffer = ByteBuffer.allocate(floatArray.length * BYTES_IN_FLOAT)
buffer.asFloatBuffer.put(floatArray);
return buffer.array();
}
public static float[] toFloatArray(byte[] byteArray) {
float[] result = new float[byteArray.length / BYTES_IN_FLOAT];
ByteBuffer.wrap(byteArray).asFloatBuffer().get(result, 0, result.length);
return result;
}
I think you want to make use of the ByteBuffer
class, which has putFloat
and getFloat
methods.
This is more for my future reference than anything else.
public static byte[] floatToByte(float[] input) {
byte[] ret = new byte[input.length*4];
for (int x = 0; x < input.length; x++) {
ByteBuffer.wrap(ret, x*4, 4).putFloat(input[x]);
}
return ret;
}
public static float[] byteToFloat(byte[] input) {
float[] ret = new float[input.length/4];
for (int x = 0; x < input.length; x+=4) {
ret[x/4] = ByteBuffer.wrap(input, x, 4).getFloat();
}
return ret;
}
Can be reduced to a single line like https://stackoverflow.com/a/44104399/322017.
Another way... use ByteArrayOutputStream/DataOutputStream for output
float fArr[] = ...;
ByteArrayOutputStream bas = new ByteArrayOutputStream();
DataOutputStream ds = new DataOutputStream(bas);
for (float f : fArr)
ds.writeFloat(f);
byte[] bytes = bas.toByteArray();
Use ByteArrayInputStream/DataInputStream for input
byte[] buffer = ...;
ByteArrayInputStream bas = new ByteArrayInputStream(buffer);
DataInputStream ds = new DataInputStream(bas);
float[] fArr = new float[buffer.length / 4]; // 4 bytes per float
for (int i = 0; i < fArr.length; i++)
{
fArr[i] = ds.readFloat();
}
Use Float.floatToIntBits()
to extract the bit-value of the float as an integer, then use BigInteger.toByteArray()
to make a byte[]
. This can be reversed using the BigInteger
constructor that takes a byte[]
argument, and then Float.intBitsToFloat()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With