8

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?

2
  • Not sure if I got your question right, could you please confirm: You have a byte array of size 8 which stores a 40 bit key (that is 5 bytes) and you want to left-pad (or prepend) the unset bits (or 0's) until 56th bit. Is my understanding right? Commented Oct 20, 2013 at 7:56
  • yea you are right i believe. Commented Oct 20, 2013 at 8:01

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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));
}

2 Comments

I would use System.out.println(Arrays.toString(array)); in the method printArray(byte[] array) to print out an array
Sure, good remark. I'm using basic java arrays really rare :)
2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.