3

每次进入某个循环时,我都需要增加一个 32 位的值。但是,最终它必须是字节数组(byte[])形式。最好的方法是什么?

选项1:

byte[] count = new byte[4];
//some way to initialize and increment byte[]

选项 2:

int count=0;
count++;
//some way to convert int to byte

选项 3:??

4

2 回答 2

3

您将转换intbyte[]如下:

ByteBuffer b = ByteBuffer.allocate(4);
//b.order(ByteOrder.BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN.
b.putInt(0xAABBCCDD);

byte[] result = b.array();  

来源:将整数转换为字节数组(Java)

现在是增量部分。你可以像你一样增加你的整数。使用++或任何需要。然后,清除ByteBuffer,再次输入数字,flip()缓冲区并获取数组

于 2013-10-26T04:21:58.987 回答
-1

另一种方便的方法是以下方法,它也适用于任意长度的字节数组:

byte[] counter = new byte[4]; // all zeroes
byte[] incrementedCounter = new BigInteger(1, counter).add(BigInteger.ONE).toByteArray();
if (incrementedCounter.length > 4) {
    incrementedCounter = ArrayUtils.subarray(incrementedCounter, 1, incrementedCounter.length);
}
else if (incrementedCounter.length < 5) {
   incrementedCounter = ArrayUtils.addAll(new byte[5-incrementedCounter.length], incrementedCounter);
}
// do something with the counter
...
counter = incrementedCounter ;

计数器将在 2^32 位后溢出。因为 BigInteger 也使用了一个符号位,所以可能需要切断一个额外的前导字节(在代码中完成)。溢出在这里由这个 cut 处理并再次从 0 开始。

ArrayUtils是从org.apache.commons图书馆来的。

于 2019-06-13T15:31:38.557 回答