【问题标题】:How do I initialize and increment a byte array in Java?如何在 Java 中初始化和递增字节数组?
【发布时间】:2013-10-26 04:14:53
【问题描述】:
每次进入某个循环时,我都需要增加一个 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:??
【问题讨论】:
标签:
java
arrays
int
bytearray
【解决方案1】:
您可以将int 转换为byte[],如下所示:
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();
来源:Convert integer into byte array (Java)
现在是增量部分。你可以像你一样增加你的整数。使用++ 或任何需要。然后,清空ByteBuffer,重新输入数字,flip()缓冲区,得到数组
【解决方案2】:
另一种方便的方法是以下方法,它也适用于任意长度的字节数组:
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 库。