david david - 6 months ago 49
Java Question

How to make a byte array with first eight bytes as current timestamp?

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.


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);
byte[] timeBytes = buffer.array();
System.arraycopy(timeBytes, 0, payload, 0, timeBytes.length);