last Index Of byte in byte array by offset and limit - Java java.lang

Java examples for java.lang:byte Array

Description

last Index Of byte in byte array by offset and limit

Demo Code


//package com.java2s;

import java.nio.ByteBuffer;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] text = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int offset = 2;
        int limit = 2;
        byte[] s = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(lastIndexOf(text, offset, limit, s));
    }/*from  ww  w .java2s . co m*/

    public final static int lastIndexOf(final byte[] text,
            final int offset, final int limit, final byte[] s) {
        final int len = s.length;
        if (limit >= len) {
            final int size = limit - len + 1;
            for (int i = size - 1; i >= offset; i--) {
                if (equals(text, i, s, 0, len)) {
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     *
     * @param array
     * @param offset
     *            absolute
     * @param limit
     *            absolute
     * @param b
     * @return absolute
     */
    public final static int lastIndexOf(final byte[] array,
            final int offset, final int limit, final byte b) {
        for (int i = limit - 1; i >= offset; i--) {
            if (array[i] == b) {
                return i;
            }
        }
        return -1;
    }

    public final static boolean equals(final byte[] array1,
            final int start1, final byte[] array2, final int start2,
            final int len) {
        if (start1 + len > array1.length || start2 + len > array2.length) {
            return false;
        }
        for (int i = 0; i < len; i++) {
            if (array1[start1 + i] != array2[start2 + i]) {
                return false;
            }
        }
        return true;
    }

    public final static boolean equals(final byte[] array1,
            final int offset1, final int end1, final byte[] array2,
            final int offset2, final int end2) {
        final int len1 = end1 - offset1;
        final int len2 = end2 - offset2;
        if (len1 != len2) {
            return false;
        } else {
            return equals(array1, offset1, array2, offset2, len1);
        }
    }

    public final static boolean equals(final byte[] array1,
            final int offset1, final byte[] array2) {
        return equals(array1, offset1, array2, 0, array2.length);
    }

    public final static boolean equals(final ByteBuffer bb1,
            final ByteBuffer bb2) {
        final byte[] array1 = bb1.array();
        final byte[] array2 = bb2.array();
        final int end1 = bb1.limit();
        final int end2 = bb2.limit();
        return equals(array1, 0, end1, array2, 0, end2);
    }
}

Related Tutorials