Splits a byte array input into two arrays at index, i.e. - Java java.lang

Java examples for java.lang:byte Array to int

Description

Splits a byte array input into two arrays at index, i.e.

Demo Code

/*******************************************************************************
 * Copyright (c) 2008 JCrypTool Team and Contributors
 * //from w ww.j a v  a  2s  .  co m
 * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] input = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int index = 2;
        System.out.println(java.util.Arrays.toString(split(input, index)));
    }

    /**
     * Splits a byte array <code>input</code> into two arrays at <code>index</code>, i.e. the first array will have
     * <code>index</code> bytes, the second one <code>input.length - index</code> bytes.
     * 
     * @param input - the byte array to be split
     * @param index - the index where the byte array is split
     * 
     * @return the two halfs of <code>input</code> as an array of two byte arrays
     */
    public static byte[][] split(byte[] input, int index) {
        if (input == null || index > input.length) {
            return null;
        }
        byte[][] result = new byte[2][];
        result[0] = new byte[index];
        result[1] = new byte[input.length - index];
        System.arraycopy(input, 0, result[0], 0, index);
        System.arraycopy(input, index, result[1], 0, input.length - index);
        return result;
    }
}

Related Tutorials