ByteBuffer alignmentOffset() in Java

alignmentOffset(): This method is available in java.nio.ByteBuffer class of Java.

Syntax:

int java.nio.ByteBuffer.alignmentOffset(int index, int unitSize)

This method takes two arguments of type int as its parameter. This method returns the memory address, pointing to the byte at the given index,modulo the given unit size.

Note: The return value is non-negative in the range of 0(inclusive) up to unitSize (exclusive), with zero indicating that the address of the byte at the index is aligned for the unit size,and a positive value that the address is misaligned for the unit size.

Parameters: Two parameters are required for this method.

index: The index to query for alignment offset, must be non-negative, no upper bounds check is performed.

unitSize: The unit size in bytes, must be a power of 2.

Returns: The indexed byte's memory address modulo the unit size.

Throws:

1. IllegalArgumentException - If the index is negative or the unit size is not a power of 2.

2. UnsupportedOperationException - If the native platform does not guarantee stable alignment offset values for the given unit size when managing the memory regions of buffers of the same kind as this buffer (direct or non-direct).

Approach 1: When no exceptions.

Java

import java.nio.ByteBuffer;

public class ByteBufferalignmentOffset {
    public static void main(String[] args) {

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);
        int index = 0, unitSize = 4;
        System.out.println(bb.alignmentOffset(index, unitSize));

    }
}

Output:

0


Approach 2: IllegalArgumentException 

Java

import java.nio.ByteBuffer;

public class ByteBufferalignmentOffset {
    public static void main(String[] args) {

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);
        int index = 0, unitSize = 5;
        System.out.println(bb.alignmentOffset(index, unitSize));

    }
}


Output:

Exception in thread "main" java.lang.IllegalArgumentException: Unit size not a power of two: 5 at java.base/java.nio.ByteBuffer.alignmentOffset(ByteBuffer.java:2033)


Approach 3: UnsupportedOperationException 

Java

import java.nio.ByteBuffer;

public class ByteBufferalignmentOffset {
    public static void main(String[] args) {

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);
        int index = 0, unitSize = 16;
        System.out.println(bb.alignmentOffset(index, unitSize));

    }
}


Output:

Exception in thread "main" java.lang.UnsupportedOperationException: Unit size unsupported for non-direct buffers: 16 at java.base/java.nio.ByteBuffer.alignmentOffset(ByteBuffer.java:2035)


No comments:

Post a Comment