转换LongBuffer / IntBuffer / ShortBuffer到的ByteBuffer [英] convert a LongBuffer/IntBuffer/ShortBuffer to ByteBuffer
问题描述
我知道一个快速的方法来转换一个字节/短路/ INT /长数组的ByteBuffer,然后获取一个字节数组。例如,要转换成字节数组短阵我可以这样做:
I know a quick way to convert a byte/short/int/long array to ByteBuffer, and then obtain a byte array. For instance, to convert a byte array to short array I can do:
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);
产生一个短阵这样的: [256,0,0,0,256,0,0,0]
我能如何使用 java的反向操作。 NIO 类?
How can I do the inverse operation using java.nio classes?
现在我这样做:
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();
和我获得原始 [1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0]
字节数组。但我想用这样的ShortBuffer.asByteBuffer()的方法,而不是一个手动循环来做到这一点。
And I obtain the original [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
byte array. But I want to use a method like ShortBuffer.asByteBuffer(), not a manual loop to do it.
我已经找到了要求2001年的太阳,但他们没有接受。 - ((
I have found a request to Sun of 2001, but they did not accept it ;-((
推荐答案
这个怎么样?
bb.asShortBuffer().put(shortArray);
然后 BB
包含您的数据。
展开code
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!
}
}
这篇关于转换LongBuffer / IntBuffer / ShortBuffer到的ByteBuffer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!