Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert float[] to byte[] to float[] again

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.

like image 246
brain56 Avatar asked Feb 19 '12 04:02

brain56


5 Answers

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;
}
like image 131
MA90 Avatar answered Oct 14 '22 22:10

MA90


I think you want to make use of the ByteBuffer class, which has putFloat and getFloat methods.

like image 23
Dawood ibn Kareem Avatar answered Oct 17 '22 20:10

Dawood ibn Kareem


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.

like image 30
Nicolas Avatar answered Oct 17 '22 21:10

Nicolas


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();
}
like image 6
ricosrealm Avatar answered Oct 17 '22 22:10

ricosrealm


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().

like image 3
Jim Garrison Avatar answered Oct 17 '22 22:10

Jim Garrison