Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize and increment a byte array in Java?

Tags:

java

arrays

int

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

like image 745
sbhatla Avatar asked Sep 08 '26 17:09

sbhatla


1 Answers

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

like image 103
An SO User Avatar answered Sep 11 '26 06:09

An SO User