codeObserver codeObserver - 3 months ago 21x
Java Question

Convert long to byte array and add it to another array

I want to change a values in byte array to put a long timestamp value in in the MSBs. Can someone tell me whats the best way to do it. I do not want to insert values bit-by-bit which I believe is very inefficient.

long time = System.currentTimeMillis();
Long timeStamp = new Long(time);
byte[] bArray = new byte[128];

What I want is something like:

byte[0-63] = timeStamp.byteValue();

Is something like this possible . What is the best way to edit/insert values in this byte array. since byte is a primitive I dont think there are some direct implementations I can make use of?


It seems that
is faster than
, so replacing the above code by it.Please correct me if wrong.


There are multiple ways to do it:

  • Use a ByteBuffer (best option - concise and easy to read):

    byte[] bytes = ByteBuffer.allocate(Long.SIZE / Byte.SIZE).putLong(someLong).array();
  • You can also use DataOutputStream (more verbose):

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    byte[] longBytes = baos.toByteArray();
  • Finally, you can do this manually (taken from the LongSerializer in Hector's code) (harder to read):

    byte[] b = new byte[8];
    for (int i = 0; i < size; ++i) {
      b[i] = (byte) (l >> (size - i - 1 << 3));

Then you can append these bytes to your existing array by a simple loop:

// change this, if you want your long to start from 
// a different position in the array
int start = 0; 
for (int i = 0; i < longBytes.length; i ++) {
   bytes[start + i] = longBytes[i];