1

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.

4
  • Presumably you want the byte order to be the same as the native one? Commented May 21, 2020 at 8:33
  • As far as I know the byte order in Java is defined by the standard? So it is not like in C where byte order depends on the architecture? Commented May 21, 2020 at 8:56
  • That's true. Java uses big endian. But you might use a different byte order if you were, say, sending this data to a little endian device, right? Commented May 21, 2020 at 9:01
  • If I understood correctly how things work Java's big endian matches with network endinaness, which is my intention here (I intend to send the data via an UDP packet). Hence I do not need to use native order Commented May 21, 2020 at 11:02

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

From somewhere else I got -related to this example-: byte[] totalByte = ByteBuffer.allocate(4).putInt(this.total).array(); why .array() is used there but not in your example?
@M.E. I used .array() in my code as well. It's to get a byte[] from a ByteBuffer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.