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: ??
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With