How to add padding on to a byte array?

An 8 byte array is of 64 bits. If you initialize the array as

byte[] aKey = new byte [8]

all bytes are initialized with 0's. If you set the first 40 bits, that is 5 bytes, then your other 3 bytes, i.e, from 41 to 64 bits are still set to 0. So, you have by default from 41st bit to 56th bit set to 0 and you don't have to reset them.

However, if your array is already initialized with some values and you want to clear the bits from 41 to 56, there are a few ways to do that.

First: you can just set aKey[5] = 0 and aKey[6] = 0 This will set the 6th bye and the 7th byte, which make up from 41st to 56th bit, to 0

Second: If you are dealing with bits, you can also use BitSet. However, in your case, I see first approach much easier, especially, if you are pre Java 7, some of the below methods do not exist and you have to write your own methods to convert from byte array to bit set and vice-versa.

byte[] b = new byte[8];
BitSet bitSet = BitSet.valueOf(b);
bitSet.clear(41, 56); //This will clear 41st to 56th Bit
b = bitSet.toByteArray();

Note: BitSet.valueOf(byte[]) and BitSet.toByteArray() exists only from Java 7.


Use System.arraycopy() to insert two bytes (56-40 = 16 bit) at the start of your array.

static final int PADDING_SIZE = 2;

public static void main(String[] args) {
    byte[] aKey = {1, 2, 3, 4, 5, 6, 7, 8}; // your array of size 8
    System.out.println(Arrays.toString(aKey));
    byte[] newKey = new byte[8];
    System.arraycopy(aKey, 0, newKey, PADDING_SIZE, aKey.length - PADDING_SIZE); // right shift
    System.out.println(Arrays.toString(newKey));
}