如何在Java中将字节数组作为shorts访问

9

我有一个大小为n的字节数组,实际上表示了一个大小为n/2的short数组。在将该数组写入磁盘文件之前,我需要通过添加另一个short数组中存储的偏移值来调整这些值。在C++中,我只需将字节数组的地址分配给一个带有short强制转换的指针,然后使用指针算术或使用联合即可。

在Java中应该如何实现 - 顺便说一下,我对Java非常陌生。

3个回答

9

你可以自己进行位操作,但我建议看一下 ByteBufferShortBuffer 类。

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.

谢谢,你和亚历山大给了我我所需要的。 - Nate Lockwood
1
如果您想循环遍历它们,可以使用 while (sb.hasRemaining())。http://docs.oracle.com/javase/6/docs/api/java/nio/Buffer.html#hasRemaining() - Raekye

8

您可以使用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

4
正确的方法是使用移位操作。因此,应该这样做:
for (int i = 0; i < shorts.length; i++) {
    shorts[i] = (short)((bytes[2*i] << 8) | bytes[2*i + 1]);
}

此外,在许多方面它取决于流的字节序。这可能会更好地工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接