Java String Pad Left leftPad(byte[] data, int size, byte pad)

Here you can find the source of leftPad(byte[] data, int size, byte pad)

Description

Pad a byte array with leading bytes.

License

Open Source License

Parameter

Parameter Description
data Data that needs padding
size The final desired size of the data.
pad The byte value to use in padding the data.

Return

A padded array.

Declaration

public static byte[] leftPad(byte[] data, int size, byte pad) 

Method Source Code

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

public class Main {
    /**//from  w w w . j  a  v  a 2s.com
     * Pad a byte array with leading bytes.
     *
     * @param data Data that needs padding
     * @param size The final desired size of the data.
     * @param pad  The byte value to use in padding the data.
     * @return A padded array.
     */
    public static byte[] leftPad(byte[] data, int size, byte pad) {
        if (size <= data.length) {
            return data;
        }

        byte[] newData = new byte[size];
        for (int i = 0; i < size; i++) {
            newData[i] = pad;
        }
        for (int i = 0; i < data.length; i++) {
            newData[size - i - 1] = data[data.length - i - 1];
        }

        return newData;
    }
}

Related

  1. leftAlignedPaddedString(String input, int length)
  2. leftPad(final String input, final int size)
  3. leftPad(final String numStr, final int numDigits)
  4. leftPad(final String str, final int size, String padStr)
  5. leftPad(final String value, final int length, final char paddingChar)