Add padding to a byte array. - Java java.lang

Java examples for java.lang:byte Array

Description

Add padding to a byte array.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] buffer = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        byte paddingByte = 2;
        int paddingLength = 2;
        System.out.println(java.util.Arrays.toString(Pad(buffer,
                paddingByte, paddingLength)));
    }/*from   w w w  .ja v  a2 s  .  c  om*/

    /**
     * Add padding to a byte array.
     * @param buffer
     * @param paddingByte
     * @param paddingLength
     * @return
     */
    public static byte[] Pad(byte[] buffer, byte paddingByte,
            int paddingLength) {
        return Concat(buffer,
                CreatePaddingBuffer(paddingByte, paddingLength));
    }

    public static byte[] Concat(byte[] buffer1, byte[] buffer2) {
        byte[] concatedArray = new byte[buffer1.length + buffer2.length];
        System.arraycopy(buffer1, 0, concatedArray, 0, buffer1.length);
        System.arraycopy(buffer2, 0, concatedArray, buffer1.length,
                buffer2.length);
        return concatedArray;

    }

    /**
     * Create a padding buffer.
     * @param paddingByte
     * @param paddingLength
     * @return
     */
    public static byte[] CreatePaddingBuffer(byte paddingByte,
            int paddingLength) {
        byte[] pading = new byte[paddingLength];
        for (int i = 0; i < pading.length; i++) {
            pading[i] = paddingByte;
        }

        return pading;
    }
}

Related Tutorials