Check whether some part or whole of two byte arrays is equal, for length bytes starting at some offset. - Java java.lang

Java examples for java.lang:byte Array Compare

Description

Check whether some part or whole of two byte arrays is equal, for length bytes starting at some offset.

Demo Code

/*//from w w  w . j a va 2s.co  m
 * Copyright (C)2016 - SMBJ Contributors
 *
 * Licensed 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.
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] a1 = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int a1Offset = 2;
        byte[] a2 = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int a2Offset = 2;
        int length = 2;
        System.out.println(equals(a1, a1Offset, a2, a2Offset, length));
    }

    /**
     * Check whether some part or whole of two byte arrays is equal, for <code>length</code> bytes starting at some
     * offset.
     *
     * @param a1
     * @param a1Offset
     * @param a2
     * @param a2Offset
     * @param length
     * @return <code>true</code> or <code>false</code>
     */
    public static boolean equals(byte[] a1, final int a1Offset, byte[] a2,
            final int a2Offset, final int length) {
        if (a1.length < a1Offset + length || a2.length < a2Offset + length) {
            return false;
        }

        for (int l = 0; l < length; l++) {
            if (a1[a1Offset + l] != a2[a2Offset + l])
                return false;
        }
        return true;
    }
}

Related Tutorials