如何在Java中初始化和递增字节数组?

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:??

1
这个链接可能对你有用:https://dev59.com/DWw15IYBdhLWcg3w0fKh - SpringLearner
2个回答

3
您可以按照以下方式将您的 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();  

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

现在是自增部分。您可以使用++或其他方式自增整数。然后清除ByteBuffer,再次输入数字,翻转缓冲区并获取数组。


-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也使用了一个符号位,可能需要剪掉一个额外的前导字节(在代码中完成)。这个溢出是通过这个剪切和重新从0开始处理的。

ArrayUtils来自org.apache.commons库。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接