1

I am making a byte array with predefined size as shown below:

private byte[] newPayload() {
  byte[] payload = new byte[100];
  Arrays.fill(payload, (byte) 1);
  return payload;
}

Now I want to add 8 bytes of current timestamp in the same byte array in front of it.

long time = System.currentTimeMillis();

So first eight bytes will be current timestamp and remaining 92 bytes will be same what I am doing right now.

john
  • 11,311
  • 40
  • 131
  • 251

1 Answers1

2

You can use ByteBuffer to convert long to byte[]. Also you can use System.arraycopy to copy this byte[] to the mail array. Please refer the below code.

ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
buffer.putLong(time);
byte[] timeBytes = buffer.array();
System.arraycopy(timeBytes, 0, payload, 0, timeBytes.length);
Jos
  • 2,015
  • 1
  • 17
  • 22
  • It looks like, I cannot find BYTES for Long class? I only see size? – john Nov 01 '16 at 18:43
  • you can try (`Long.SIZE / Byte.SIZE`) – Jos Nov 01 '16 at 18:45
  • Also let's say If I have this new byte array, now how can I extract first 8 bytes from payload byte array and convert them to long and print it out? – john Nov 01 '16 at 20:13
  • hope this will help.. http://stackoverflow.com/questions/4485128/how-do-i-convert-long-to-byte-and-back-in-java – Jos Nov 01 '16 at 20:17
  • yes but how will I extract the first eight bytes only from the byte array? – john Nov 01 '16 at 20:18
  • you can use `Arrays#copyOfRange` to extract the bytes to a separate array. https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOfRange(byte[],%20int,%20int) – Jos Nov 01 '16 at 20:20
  • so something like this? `byte[] newBytes = Arrays.copyOfRange(payload, 0, 7);` – john Nov 01 '16 at 20:21
  • yup.. that should work.. to be accurate you can give `byte[] newBytes = Arrays.copyOfRange(payload, 0, (Long.SIZE / Byte.SIZE - 1));` – Jos Nov 01 '16 at 20:23