Search code examples
javaarraysshort

How can I access a byte array as shorts in Java


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.


Solution

  • 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