每次进入某个循环时,我都需要递增一个 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:??
最佳答案
您可以将 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()
缓冲区,得到数组
关于java - 如何在 Java 中初始化和递增字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19602740/