Java Byte Array Create newByteArray(byte[] data, int finalSize)

Here you can find the source of newByteArray(byte[] data, int finalSize)

Description

Generates a new byte array of the given size using the given data and filling with ASCII zeros (0x48) the remaining space.

License

Mozilla Public License

Parameter

Parameter Description
data Data to use in the new array.
finalSize Final size of the array.

Exception

Parameter Description
IllegalArgumentException if finalSize < 0.
NullPointerException if data == null.

Return

Final byte array of the given size containing the given data and replacing with zeros the remaining space.

Declaration

public static byte[] newByteArray(byte[] data, int finalSize) 

Method Source Code

//package com.java2s;
/**//from ww  w.  j a v  a 2 s.co  m
 * Copyright (c) 2014-2016 Digi International Inc.,
 * All rights not expressly granted are reserved.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Digi International Inc. 11001 Bren Road East, Minnetonka, MN 55343
 * =======================================================================
 */

public class Main {
    /**
     * Generates a new byte array of the given size using the given data and 
     * filling with ASCII zeros (0x48) the remaining space.
     * 
     * <p>If new size is lower than current, array is truncated.</p>
     * 
     * @param data Data to use in the new array.
     * @param finalSize Final size of the array.
     * 
     * @return Final byte array of the given size containing the given data and
     *         replacing with zeros the remaining space.
     * 
     * @throws IllegalArgumentException if {@code finalSize < 0}.
     * @throws NullPointerException if {@code data == null}.
     */
    public static byte[] newByteArray(byte[] data, int finalSize) {
        if (data == null)
            throw new NullPointerException("Data cannot be null.");
        if (finalSize < 0)
            throw new IllegalArgumentException("Final size must be equal or greater than 0.");

        if (finalSize == 0)
            return new byte[0];

        byte[] filledArray = new byte[finalSize];
        int diff = finalSize - data.length;
        if (diff >= 0) {
            for (int i = 0; i < diff; i++)
                filledArray[i] = '0';
            System.arraycopy(data, 0, filledArray, diff, data.length);
        } else
            System.arraycopy(data, 0, filledArray, 0, finalSize);
        return filledArray;
    }
}

Related

  1. byteArrayFromInteger(int integer)
  2. bytes(final byte... elements)
  3. bytes(final int... ints)
  4. bytes(int... bytes)
  5. bytes(int... ints)
  6. newByteArray(int len)
  7. newByteArray(int size)
  8. newByteArray(int... bytes)
  9. newByteArray(int... bytes)