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

前端 未结 8 1608
伪装坚强ぢ
伪装坚强ぢ 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 15:55

    You need to use the getFloat() and putFloat() commands in the FloatBuffer of the ByteBuffer. In fact, you should certainly do this simply because of the sheer speed. And it's a great thing to understand for byte manipulations. You can also mix and match the data, and put and get it as needed. All of it is backed by the byte buffer. So the common happening of sending an array, you need to send the size of the array too.

    public static void writeFloatArray(float[] array, OutputStream stream) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(4 * (array.length + 1)).putInt(array.length);
        buffer.asFloatBuffer().put(array,0,array.length);
        stream.write(buffer.array());
    }
    

    You just make sure to allocate enough bytes to store everything in the buffer. Write some stuff, write some other stuff etc. Understanding this point makes things way easier. On the flipside we do basically the same thing, though we require an additional read because we don't know how big the array is, just that there is one:

    public static float[] readFloatArray(InputStream in) throws IOException {
        byte[] data = new byte[4];
        if (readFully(in, data) != data.length) return null;
        int length = ByteBuffer.wrap(data).getInt();
        data = new byte[length * 4];
        if (readFully(in,data) != data.length) return null;
        float[] array = new float[length];
        ByteBuffer.wrap(data).asFloatBuffer().get(array,0,array.length);
        return array;
    }
    

    And for full functionality, though not exactly part of this:

    public static int readFully(InputStream in, byte[] data) throws IOException {
        int offset = 0;
        int bytesRead;
        boolean read = false;
        while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) {
            read = true;
            offset += bytesRead;
            if (offset >= data.length) {
                break;
            }
        }
        return (read) ? offset : -1;
    }
    

提交回复
热议问题