How to use byte array as a short article in Java

I have a byte array with size n. this array really represents n / 2 with different sizes Before writing an array to a disk file, I need to adjust the value by adding an offset value stored in another array In C, I will assign the address of a byte array to a pointer to a short array and use pointer arithmetic or a union

How to do this in Java - I'm new to Java btw

Solution

You can use Java nio. ByteBuffer wraps an array of bytes

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 content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>