9

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 Answers 3

9

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, you and Alexander have provided me with what I need.
You can use while (sb.hasRemaining()) if you want to loop over all of them docs.oracle.com/javase/6/docs/api/java/nio/…
8

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

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.