Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2015 Institute for Pervasive Computing, ETH Zurich and others.
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 * 
 * The Eclipse Public License is available at
 *    http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 *    http://www.eclipse.org/org/documents/edl-v10.html.
 * 
 * Contributors:
 *    Matthias Kovatsch - creator and main architect
 *    Stefan Jucker - DTLS implementation
 ******************************************************************************/

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

public class Main {
    /**
     * 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;
    }
}