Compares two regions of bytes, indicating whether one is larger than the other. - Java java.lang

Java examples for java.lang:byte Array Compare

Description

Compares two regions of bytes, indicating whether one is larger than the other.

Demo Code

/* /*from  w  w w  . ja va  2 s. c om*/
 * Licensed to Aduna under one or more contributor license agreements.  
 * See the NOTICE.txt file distributed with this work for additional 
 * information regarding copyright ownership. 
 *
 * Aduna licenses this file to you under the terms of the Aduna BSD 
 * License (the "License"); you may not use this file except in compliance 
 * with the License. See the LICENSE.txt file distributed with this work 
 * for the full License.
 *
 * 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.
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] array1 = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int startIdx1 = 2;
        byte[] array2 = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int startIdx2 = 2;
        int length = 2;
        System.out.println(compareRegion(array1, startIdx1, array2,
                startIdx2, length));
    }

    /**
     * Compares two regions of bytes, indicating whether one is larger than the
     * other.
     * 
     * @param array1
     *        The first byte array.
     * @param startIdx1
     *        The start of the region in the first array.
     * @param array2
     *        The second byte array.
     * @param startIdx2
     *        The start of the region in the second array.
     * @param length
     *        The length of the region that should be compared.
     * @return A negative number when the first region is smaller than the
     *         second, a positive number when the first region is larger than the
     *         second, or 0 if the regions are equal.
     */
    public static int compareRegion(byte[] array1, int startIdx1,
            byte[] array2, int startIdx2, int length) {
        int result = 0;
        for (int i = 0; result == 0 && i < length; i++) {
            result = (array1[startIdx1 + i] & 0xff)
                    - (array2[startIdx2 + i] & 0xff);
        }
        return result;
    }
}

Related Tutorials