Java ByteBuffer Compare compareSubArrays(ByteBuffer bytes1, int offset1, ByteBuffer bytes2, int offset2, int length)

Here you can find the source of compareSubArrays(ByteBuffer bytes1, int offset1, ByteBuffer bytes2, int offset2, int length)

Description

Compare two ByteBuffer at specified offsets for length.

License

Apache License

Parameter

Parameter Description
bytes1 First byte buffer to compare.
offset1 Position to start the comparison at in the first array.
bytes2 Second byte buffer to compare.
offset2 Position to start the comparison at in the second array.
length How many bytes to compare?

Return

-1 if byte1 is less than byte2, 1 if byte2 is less than byte1 or 0 if equal.

Declaration

public static int compareSubArrays(ByteBuffer bytes1, int offset1, ByteBuffer bytes2, int offset2, int length) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.nio.ByteBuffer;

public class Main {
    /**//from  w  ww. ja  v a 2s.  c  o  m
    * Compare two ByteBuffer at specified offsets for length.
    * Compares the non equal bytes as unsigned.
    * @param bytes1 First byte buffer to compare.
    * @param offset1 Position to start the comparison at in the first array.
    * @param bytes2 Second byte buffer to compare.
    * @param offset2 Position to start the comparison at in the second array.
    * @param length How many bytes to compare?
    * @return -1 if byte1 is less than byte2, 1 if byte2 is less than byte1 or 0 if equal.
    */
    public static int compareSubArrays(ByteBuffer bytes1, int offset1, ByteBuffer bytes2, int offset2, int length) {
        if (null == bytes1) {
            if (null == bytes2)
                return 0;
            else
                return -1;
        }
        if (null == bytes2)
            return 1;

        assert bytes1.limit() >= offset1
                + length : "The first byte array isn't long enough for the specified offset and length.";
        assert bytes2.limit() >= offset2
                + length : "The second byte array isn't long enough for the specified offset and length.";
        for (int i = 0; i < length; i++) {
            byte byte1 = bytes1.get(offset1 + i);
            byte byte2 = bytes2.get(offset2 + i);
            if (byte1 == byte2)
                continue;
            // compare non-equal bytes as unsigned
            return (byte1 & 0xFF) < (byte2 & 0xFF) ? -1 : 1;
        }
        return 0;
    }
}

Related

  1. compareToP(ByteBuffer bb1, ByteBuffer bb2)
  2. compareUnsigned(ByteBuffer o1, ByteBuffer o2)