UnsupportedOperationException with converting byte[] to float[]

前端 未结 3 1993
没有蜡笔的小新
没有蜡笔的小新 2021-02-15 01:57

I\'m trying to convert a byte[] to a float[] by putting the byte[] in a ByteBuffer, converting this to a FloatBuffer (.asFloatBuffer), and then converting this to a

3条回答
  •  花落未央
    2021-02-15 02:34

    public static float[] toFloatArray(byte[] bytes) {
        float[] floats = new float[bytes.length/4];
        ByteBuffer.wrap(bytes).asFloatBuffer().get(floats).array();
        return floats;
    }
    

    The reason why you can't do return ByteBuffer.wrap(bytes).asFloatBuffer().array(); is that it creates a view of this byte buffer as a float buffer. Which means it's using the same memory. It's lightning fast, but needs a place to put it in memory that isn't being treated as a float[] AND byte[] hence why it can't give you the data back without new memory.

    public static void convertFloatArray(byte[] bytes, float[] floats) {
        ByteBuffer.wrap(bytes).asFloatBuffer().get(floats,0,bytes.length/4);
    }
    

    It's just the class doesn't make its own memory but fiddles with the memory you give it, which is awesome, but could be confusing at times.

提交回复
热议问题