M.E.
M.E.

Reputation: 5495

How do I put an integer inside a byte array at a given location?

I want to fill in a byte array with variables at given positions.

As a minimal example, below's code tries to insert an int variable at location 10 of a byte array (which would use bytes 10,11,12 and 13 of the byte array).

public class HelloWorld{

     public static void main(String []args){

       // DESTIONATION BYTE ARRAY
       byte[] myByteArray = new byte[64];

       // INTEGER
       int myInt = 542323;

       // I WANT TO PUT myInt AT POSITION 10 IN myByteArray
       // PSEUDOCODE BELOW:
       myByteArray.putInt(myInt, 10);

     }
}

I am not sure which alternatives do I have to copy an int directly to a given location of a larger byte array.

Upvotes: 0

Views: 785

Answers (1)

Sweeper
Sweeper

Reputation: 271505

One way to do this is to use a ByteBuffer, which already has the logic of splitting the int into 4 bytes baked in:

byte[] array = new byte[64];

ByteBuffer buffer = ByteBuffer.allocate(4);
// buffer.order(ByteOrder.nativeOrder()); // uncomment if you want native byte order
buffer.putInt(542323);

System.arraycopy(buffer.array(), 0, array, 10, 4);
//                                         ^^
//                        change the 10 here to copy it somewhere else

Of course, this creates an extra byte array and byte buffer object, which could be avoided if you just use bit masks:

int x = 542323;
byte b1 = (x >> 24) & 0xff;
byte b2 = (x >> 16) & 0xff;
byte b3 = (x >> 8) & 0xff;
byte b4 = x & 0xff;

// or the other way around, depending on byte order 
array[10] = b4;
array[11] = b3;
array[12] = b2;
array[13] = b1;

Upvotes: 1

Related Questions