如何在 Java 中以短裤的形式访问字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2496661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I access a byte array as shorts in Java
提问by Nate Lockwood
I have a an array of byte, size n, that really represents an array of short of size n/2. Before I write the array to a disk file I need to adjust the values by adding bias values stored in another array of short. In C++ I would just assign the address of the byte array to a pointer for a short array with a cast to short and use pointer arithmetic or use a union.
我有一个字节数组,大小为 n,它实际上代表了一个大小为 n/2 的数组。在将数组写入磁盘文件之前,我需要通过添加存储在另一个 short 数组中的偏差值来调整值。在 C++ 中,我只是将字节数组的地址分配给一个指向短数组的指针,并使用指向 short 的强制转换并使用指针算术或使用联合。
How may this be done in Java - I'm very new to Java BTW.
这如何在 Java 中完成 - 我对 Java BTW 很陌生。
采纳答案by Alexander Pogrebnyak
You can wrap your byte array with java.nio.ByteBuffer.
你可以用 java.nio.ByteBuffer 包装你的字节数组。
byte[] bytes = ...
ByteBuffer buffer = ByteBuffer.wrap( bytes );
// you may or may not need to do this
//buffer.order( ByteOrder.BIG/LITTLE_ENDIAN );
ShortBuffer shorts = buffer.asShortBuffer( );
for ( int i = 0, n=shorts.remaining( ); i < n; ++i ) {
final int index = shorts.position( ) + i;
// Perform your transformation
final short adjusted_val = shortAdjuster( shorts.get( index ) );
// Put value at the same index
shorts.put( index, adjusted_val );
}
// bytes now contains adjusted short values
回答by Adamski
You could do the bit-twiddling yourself but I'd recommend taking a look at the ByteBufferand ShortBufferclasses.
您可以自己进行一些操作,但我建议您查看ByteBuffer和ShortBuffer类。
byte[] arr = ...
ByteBuffer bb = ByteBuffer.wrap(arr); // Wrapper around underlying byte[].
ShortBuffer sb = bb.asShortBuffer(); // Wrapper around ByteBuffer.
// Now traverse ShortBuffer to obtain each short.
short s1 = sb.get();
short s2 = sb.get(); // etc.
回答by Luke Magill
The correct way to do this is using shifts. So
正确的方法是使用轮班。所以
for (int i = 0; i < shorts.length; i++) {
shorts[i] = (short)((bytes[2*i] << 8) | bytes[2*i + 1]);
}
Also, it depends on the endian-ness of the stream in many respects. This may work better
此外,它在许多方面取决于流的字节序。这可能效果更好

