Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright 2015 Tapcentive, Inc.
 *
 * 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.
 *
 */

public class Main {
    /**
     * Gets the tag.
     *
     * @param byteArray the byte array
     * @param lengthOfData the length of data
     * @param tag the tag
     * @param occurences the occurences
     * @return the tag
     */
    public static byte[] getTag(byte[] byteArray, int lengthOfData, short tag, int occurences) {
        int timesFound = 0;
        int i;
        boolean skip = false;
        for (i = 0; i < lengthOfData;) {
            short twoByteTag = 0;
            if ((short) (byteArray[i] & 0xff) == tag) {
                if (occurences == timesFound) {
                    byte[] dataObject = new byte[byteArray[i + 1] + 2];
                    System.arraycopy(byteArray, i, dataObject, 0, dataObject.length);
                    return dataObject;
                } else {
                    timesFound++;
                    skip = true;
                }
            }
            if ((byte) (byteArray[i] & (byte) 0x1f) == (byte) 0x1f) {
                i++;
                twoByteTag = (short) (((short) (byteArray[i - 1] & 0xff) << 8) + (short) (byteArray[i] & 0xff));
                if (twoByteTag == tag) {
                    if (occurences == timesFound) {
                        byte[] dataObject = new byte[byteArray[i + 1] + 3];
                        System.arraycopy(byteArray, i - 1, dataObject, 0, dataObject.length);
                        return dataObject;
                    } else {
                        timesFound++;
                        skip = true;
                    }
                }
            }
            // this will search within a template. assumes that any template tag is only 1 byte. will not work for 2 byte tags
            if (twoByteTag == 0 && (byte) (byteArray[i] & (byte) 0x20) == (byte) 0x20 && !skip) {
                i = i + 2;
            } else {
                i = i + byteArray[i + 1] + 2;
                skip = false;
            }
        }
        return null;
    }
}