开发者

How can I access a byte array as shorts in Java

开发者 https://www.devze.com 2022-12-23 15:43 出处:网络
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 arra

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.

How may this be done in Java - I'm ver开发者_如何学Goy new to Java BTW.


You could do the bit-twiddling yourself but I'd recommend taking a look at the ByteBuffer and ShortBuffer classes.

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.


You can wrap your byte array with 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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消