Java ByteBuffer Compare compareUnsigned(ByteBuffer o1, ByteBuffer o2)

Here you can find the source of compareUnsigned(ByteBuffer o1, ByteBuffer o2)

Description

compare Unsigned

License

Apache License

Declaration

public static int compareUnsigned(ByteBuffer o1, ByteBuffer o2) 

Method Source Code

//package com.java2s;
/*/*from  w w  w .  j a v  a  2s . c  o  m*/
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.nio.ByteBuffer;

public class Main {
    public static int compareUnsigned(ByteBuffer o1, ByteBuffer o2) {
        return compareUnsigned(o1.array(), o2.array(), o1.arrayOffset() + o1.position(),
                o2.arrayOffset() + o2.position(), o1.limit() + o1.arrayOffset(), o2.limit() + o2.arrayOffset());
    }

    private static int compareUnsigned(byte[] bytes1, byte[] bytes2, int offset1, int offset2, int len1, int len2) {
        if (bytes1 == null) {
            return bytes2 == null ? 0 : -1;
        }
        if (bytes2 == null)
            return 1;

        int minLength = Math.min(len1 - offset1, len2 - offset2);
        for (int x = 0, i = offset1, j = offset2; x < minLength; x++, i++, j++) {
            if (bytes1[i] == bytes2[j])
                continue;
            // compare non-equal bytes as unsigned
            return (bytes1[i] & 0xFF) < (bytes2[j] & 0xFF) ? -1 : 1;
        }
        if ((len1 - offset1) == (len2 - offset2))
            return 0;
        else
            return ((len1 - offset1) < (len2 - offset2)) ? -1 : 1;
    }
}

Related

  1. compareSubArrays(ByteBuffer bytes1, int offset1, ByteBuffer bytes2, int offset2, int length)
  2. compareToP(ByteBuffer bb1, ByteBuffer bb2)