Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中,如何以短路方式访问字节数组_Java_Bytearray_Short - Fatal编程技术网

在Java中,如何以短路方式访问字节数组

在Java中,如何以短路方式访问字节数组,java,bytearray,short,Java,Bytearray,Short,我有一个字节数组,大小为n,它实际上表示一个大小为n/2的数组。在将数组写入磁盘文件之前,我需要通过添加存储在另一个short数组中的偏差值来调整这些值。在C++中,我只需将字节数组的地址分配给一个短数组的指针,并使用指针运算或使用UNION/< 这在Java中是如何实现的?顺便说一句,我对Java非常陌生。你可以自己做一些事情,但我建议你看看和类 您可以使用java.nio.ByteBuffer包装字节数组 byte[] bytes = ... ByteBuffer buffer = Byte

我有一个字节数组,大小为n,它实际上表示一个大小为n/2的数组。在将数组写入磁盘文件之前,我需要通过添加存储在另一个short数组中的偏差值来调整这些值。在C++中,我只需将字节数组的地址分配给一个短数组的指针,并使用指针运算或使用UNION/<
这在Java中是如何实现的?顺便说一句,我对Java非常陌生。

你可以自己做一些事情,但我建议你看看和类


您可以使用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
byte[]bytes=。。。
ByteBuffer缓冲区=ByteBuffer.wrap(字节);
//您可能需要也可能不需要这样做
//buffer.order(ByteOrder.BIG/LITTLE_ENDIAN);
ShortBuffer shorts=buffer.asShortBuffer();
for(inti=0,n=shorts.remaining();i
正确的方法是使用轮班制。所以

for (int i = 0; i < shorts.length; i++) {
    shorts[i] = (short)((bytes[2*i] << 8) | bytes[2*i + 1]);
}
for(int i=0;ishorts[i]=(short)((bytes[2*i]谢谢,你和Alexander已经为我提供了所需的内容。如果你想循环所有内容,可以使用
while(sb.haslaining())
for (int i = 0; i < shorts.length; i++) {
    shorts[i] = (short)((bytes[2*i] << 8) | bytes[2*i + 1]);
}