views:

338

answers:

3

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 very new to Java BTW.

+3  A: 

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.
Adamski
Thanks, you and Alexander have provided me with what I need.
+1  A: 

Wrap your byte array with java.nio.ByteBuffer.

byte[] bytes = ...
ByteBuffer buffer = ByteByffer.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 = short.position( ) + i;

    // Perform your transformation
    final short adusted_val = shortAdjuster( shorts.get( index ) );

    // Put value at the same index
    shorts.put( index, adjusted_val );
}

// bytes now contains adjusted short values
Alexander Pogrebnyak
A: 

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

Luke Magill