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

前端 未结 8 1650
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 15:17

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

8条回答
  •  既然无缘
    2020-12-31 16:00

    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();
    }
    

提交回复
热议问题