Compare two byte arrays. - Java java.lang

Java examples for java.lang:byte Array Compare

Description

Compare two byte arrays.

Demo Code

/*/*from   w ww . j  av  a  2 s  . com*/
 *  Copyright 2006 Goran Ehrsson.
 *
 *  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.
 *  under the License.
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] input = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        byte[] compare = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(compareBytes(input, compare));
    }

    /**
     * Compare two byte arrays.
     * 
     * @param input the bytes to compare.
     * @param compare the reference byte array.
     * @return true if <code>input</code> starts with the same bytes as <code>compare</code>.
     */
    public static boolean compareBytes(final byte[] input,
            final byte[] compare) {
        if (input.length < compare.length) {
            return false;
        }
        for (int i = 0; i < compare.length; i++) {
            if (compare[i] != input[i]) {
                return false;
            }
        }
        return true;
    }
}

Related Tutorials