How can I get short[] from a ByteBuffer

青春壹個敷衍的年華 提交于 2019-12-08 16:43:50

问题


I am using JNI code in an Android project in which the JNI native function requires a short[] argument. However, the original data is stored as a ByteBuffer. I'm trying the convert the data format as follows.

ByteBuffer rgbBuf = ByteBuffer.allocate(size);
...    
short[] shortArray = (short[]) rgbBuf.asShortBuffer().array().clone();

But I encounter the following problem when running the second line of code shown above:

E/AndroidRuntime(23923): Caused by: java.lang.UnsupportedOperationException
E/AndroidRuntime(23923): at Java.nio.ShortToByteBufferAdapter.protectedArray(ShortToByteBufferAdapter.java:169)

Could anyone suggest a means to implement the conversion?


回答1:


The method do this is a bit odd, actually. You can do it as below; ordering it is important to convert it to a short array.

short[] shortArray = new short[size/2];
rgbBuf.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shortArray);

Additionally, you may have to use allocateDirect instead of allocate.




回答2:


I had the same error with anything that used asShortBuffer(). Here's a way around it (adapted from 2 bytes to short java):

short[] shortArray = new short[rgbBuf.capacity() / 2]);
for (int i=0; i<shortArray.length; i++)
{   
    ByteBuffer bb = ByteBuffer.allocate(2);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    bb.put(rgbBuf[2*i]);
    bb.put(rgbBuf[2*i + 1]);
    shortArray[i] = bb.getShort(0);
}


来源:https://stackoverflow.com/questions/11930385/how-can-i-get-short-from-a-bytebuffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!