Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add padding on to a byte array?

I have this 40 bit key in a byteArray of size 8, and I want to add 0 padding to it until it becomes 56 bit.

byte[] aKey = new byte [8];  // How I instantiated my byte array

Any ideas how?

like image 328
Napmi Avatar asked Oct 20 '13 07:10

Napmi


3 Answers

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.

like image 132
Srikanth Reddy Lingala Avatar answered Nov 18 '22 05:11

Srikanth Reddy Lingala


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));
}
like image 26
Stanislav Mamontov Avatar answered Nov 18 '22 06:11

Stanislav Mamontov


Guava's com.google.common.primitives.Bytes.ensureCapacity:

aKey = Bytes.ensureCapacity(aKey , 56/8, 0);

or since JDK6 using Java native tools:

aKey = java.util.Arrays.copyOf(aKey , 56/8);
like image 1
30thh Avatar answered Nov 18 '22 06:11

30thh