UnsupportedOperationException with converting byte[] to float[]

前端 未结 3 1985
没有蜡笔的小新
没有蜡笔的小新 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:36

    The simple way to get a float from a byte[] array wrapped by a ByteBuffer is to use getFloat() which reads the next 4 bytes and returns the generated float. You can do this in a loop, if your byte[] contains more than 4 bytes. Note that the method throws

    BufferUnderflowException - If there are fewer than four bytes remaining in this buffer

    You can get it from the FloatBuffer as well

    buffer.asFloatBuffer().get();
    

    if you want but array() throws an UnsupportedOperationException if the instance's hb field is null. If you look at the source code from Oracle JDK 7, there is a comment

    final float[] hb;  // Non-null only for heap buffers
    

    If you run your code, you will notice the returned FloatBuffer is a ByteBufferAsFloatBufferB, not a HeapFloatBuffer.

提交回复
热议问题