3

I need to increment a 32 bit value each time I enter a certain loop. However, eventually it must be in a byte array (byte[]) form. What is the best way to go about it?

Option 1:

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

Option 2:

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

Option 3: ??

sbhatla
  • 1,040
  • 2
  • 22
  • 34

2 Answers2

3

You would convert your int to byte[] as follows:

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();  

source: Convert integer into byte array (Java)

Now comes the increment part. You can increment your integer the same way you would do. using ++ or whatever the need be. Then, clear the ByteBuffer, put in the number again, flip() the buffer and get the array

Community
  • 1
  • 1
An SO User
  • 24,612
  • 35
  • 133
  • 221
-1

Another convenient way is the following method which works also with arbitrary length byte arrays:

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 ;

The counter will overflow after 2^32 bits. Because also a sign bit is used by BigInteger it might be necessary to cut off an additional leading byte (done in the code). The overflow is handled here by this cut and starting with 0 again.

ArrayUtils is coming from the org.apache.commons library.

k_o_
  • 5,143
  • 1
  • 34
  • 43