Splits the given array into blocks of given size and adds padding to the last one, if necessary. - Java Collection Framework

Java examples for Collection Framework:Array Auto Increment

Description

Splits the given array into blocks of given size and adds padding to the last one, if necessary.

Demo Code


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main{
    public static void main(String[] argv) throws Exception{
        byte[] byteArray = new byte[]{34,35,36,37,37,37,67,68,69};
        int blocksize = 2;
        System.out.println(java.util.Arrays.toString(splitAndPad(byteArray,blocksize)));
    }/*from www.  ja v  a 2s  . c  o m*/
    /**
     * Splits the given array into blocks of given size and adds padding to the
     * last one, if necessary.
     * 
     * @param byteArray
     *            the array.
     * @param blocksize
     *            the block size.
     * @return a list of blocks of given size.
     */
    public static List<byte[]> splitAndPad(byte[] byteArray, int blocksize) {
        List<byte[]> blocks = new ArrayList<byte[]>();
        int numBlocks = (int) Math.ceil(byteArray.length
                / (double) blocksize);

        for (int i = 0; i < numBlocks; i++) {

            byte[] block = new byte[blocksize];
            Arrays.fill(block, (byte) 0x00);
            if (i + 1 == numBlocks) {
                // the last block
                int remainingBytes = byteArray.length - (i * blocksize);
                System.arraycopy(byteArray, i * blocksize, block, 0,
                        remainingBytes);
            } else {
                System.arraycopy(byteArray, i * blocksize, block, 0,
                        blocksize);
            }
            blocks.add(block);
        }

        return blocks;
    }
}

Related Tutorials