将LongBuffer/IntBuffer/ShortBuffer转换为ByteBuffer

log*_*off 15 java arrays nio bytearray

我知道一种快速的方法将byte/short/int/long数组转换为ByteBuffer,然后获取一个字节数组.例如,要将字节数组转换为短数组,我可以这样做:

byte[] bArray = { 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 };

ByteBuffer bb = ByteBuffer.wrap(byteArray);
ShortBuffer sb = bb.asShortBuffer();
short[] shortArray = new short[byteArray.length / 2];
sb.get(shortArray);
Run Code Online (Sandbox Code Playgroud)

产生一个这样的短数组:[256, 0, 0, 0, 256, 0, 0, 0].

如何使用java.nio类进行逆操作?

现在我这样做:

shortArray[] = {256, 0, 0, 0, 256, 0, 0, 0};
ByteBuffer bb = ByteBuffer.allocate(shortArray.length * 2);
for (short s : shortArray) {
    bb.putShort(s);
}
return bb.array();
Run Code Online (Sandbox Code Playgroud)

我获得了原始的[1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]字节数组.但我想使用像ShortBuffer.asByteBuffer()这样的方法,而不是手动循环来做到这一点.

我已经向Sun发出了2001年请求,但是他们不接受它; - ((

A.H*_*.H. 28

那这个呢?:

    bb.asShortBuffer().put(shortArray);
Run Code Online (Sandbox Code Playgroud)

然后bb包含您的数据.

完整代码:

public class Test {
    public static void main(final String args[]) {
        short[] arr = { 256, 0, 0, 0, 256, 0, 0, 0 };
        for (byte b : F(arr)) {
            System.out.print(b);
        }
    }

    public static byte[] F(short[] arr) {
        java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(arr.length * 2);
        bb.asShortBuffer().put(arr);
        return bb.array(); // this returns the "raw" array, it's shared and not copied!
    }
}
Run Code Online (Sandbox Code Playgroud)