Android Array Split split(byte[] input)

Here you can find the source of split(byte[] input)

Description

Spits the input array into separate byte arrays.

License

Open Source License

Parameter

Parameter Description
input the input array

Return

a new array of byte arrays

Declaration

public static byte[][] split(byte[] input) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.nio.ByteBuffer;

import java.util.ArrayList;

public class Main {
    /**//from w w w . j  a va  2s .c  o  m
     * Spits the input array into separate byte arrays. Works similarly to <code>String.split()</code>, but always splits on a null byte (0x00).
     * @param input the input array
     * @return a new array of byte arrays
     */
    public static byte[][] split(byte[] input) {
        ByteBuffer buf; //TODO
        ByteBuffer buf2;//TODO

        ArrayList<byte[]> temp = new ArrayList<byte[]>();

        byte[][] output; //TODO be more efficient here
        output = new byte[input.length][input.length]; //excessively large, but this is the maximum size it can be (actually, less, but it's a good upper bound)
        int out_index = 0;

        int index_cache = 0;
        for (int i = 0; i < input.length; i++) {
            if (input[i] == 0x00) {
                //            output[out_index++] = subarray(input, index_cache, i-1); //store the array from the last null byte to the current one
                byte[] b = subarray(input, index_cache, i - 1);
                temp.add(b);
                index_cache = i + 1;//note, this is the index *after* the null byte
            }
        }
        //get the remaining part
        if (index_cache != 0) //prevent duplication if there are no null bytes
        {
            //         output[out_index] = subarray(input, index_cache, input.length-1);
            byte[] b = subarray(input, index_cache, input.length - 1);
            temp.add(b);
        }

        output = new byte[temp.size()][input.length];
        for (int i = 0; i < temp.size(); i++) {
            output[i] = temp.get(i);
        }

        return output;
    }

    /**
     * Creates and returns a new array with the values of the original from index <code>a</code> to index <code>b</code>
     * and of size <code>(b-a)</code>.
     * @param in input array
     * @param a first index
     * @param b last index
     * @return a new array based on the desired range of the input
     */
    public static byte[] subarray(byte[] in, int a, int b) {
        if (b - a > in.length)
            return in;// TODO better error checking

        byte[] out = new byte[(b - a) + 1];

        for (int i = a; i <= b; i++) {
            out[i - a] = in[i];
        }
        return out;
    }
}

Related

  1. byteSplit(byte[] inp, int... splitLength)