7

我有这个大小为8的40 位密钥,我想向它添加 0 填充,直到它变成56 位byteArray

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

有什么想法吗?

4

3 回答 3

9

一个 8 字节的数组是 64 位的。如果将数组初始化为

byte[] aKey = new byte [8]

所有字节都用 0 初始化。如果您设置前 40 位,即 5 个字节,那么您的其他 3 个字节,即从 41 到 64 位仍设置为 0。因此,默认情况下,您将第 41 位到第 56 位设置为 0,而您不要不必重置它们。

但是,如果您的数组已经使用一些值进行了初始化,并且您想要清除 41 到 56 之间的位,则有几种方法可以做到这一点。

第一: 您可以只设置aKey[5] = 0aKey[6] = 0这会将第 6 个字节和第 7 个字节(从第 41 位到第 56 位)设置为 0

第二:如果是处理位,也可以使用BitSet。但是,在您的情况下,我认为第一种方法更容易,特别是,如果您是 Java 7 之前的版本,则以下某些方法不存在,您必须编写自己的方法来从字节数组转换为位集,反之亦然.

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

注意:BitSet.valueOf(byte[])并且BitSet.toByteArray()仅存在于 Java 7 中。

于 2013-10-20T08:18:51.807 回答
4

使用 System.arraycopy() 在数组的开头插入两个字节(56-40 = 16 位)。

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));
}
于 2013-10-20T08:02:13.130 回答
1

番石榴的 com.google.common.primitives.Bytes.ensureCapacity

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

或者从JDK6开始使用Java原生工具:

aKey = java.util.Arrays.copyOf(aKey , 56/8);
于 2019-03-06T12:25:07.720 回答