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.