How to add padding on to a byte array?

≯℡__Kan透↙ 提交于 2019-12-07 02:07:32

问题


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?


回答1:


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.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/19474957/how-to-add-padding-on-to-a-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!