I need to make a byte array such that the first eight bytes should be current timestamp and remaining bytes should be as it is. And then from the same byte array I want to extract the timestamp which I have put in the first place.
public static void main(String[] args) {
long ts = System.currentTimeMillis();
byte[] payload = newPayload(ts);
long timestamp = bytesToLong(payload);
System.out.println(timestamp);
}
private static byte[] newPayload(long time) {
ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
byte[] payload = new byte[300];
Arrays.fill(payload, (byte) 1);
buffer.putLong(time);
byte[] timeBytes = buffer.array();
System.arraycopy(timeBytes, 0, payload, 0, timeBytes.length);
return payload;
}
public static long bytesToLong(byte[] bytes) {
byte[] newBytes = Arrays.copyOfRange(bytes, 0, (Long.SIZE / Byte.SIZE - 1));
ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
buffer.put(newBytes);
buffer.flip();// need flip
return buffer.getLong();
}
Above code gives me exception and I am not sure what's wrong?
Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.Buffer.nextGetIndex(Buffer.java:498)
at java.nio.HeapByteBuffer.getLong(HeapByteBuffer.java:406)