0

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)

1 Answer 1

2

From the documentation of Arrays.copyOfRange:

to - the final index of the range to be copied, exclusive. (This index may lie outside the array.)

Which means, you haven't put enough bytes into the buffer. So the correct way to do this is:

byte[] newBytes = Arrays.copyOfRange(bytes, 0, Long.SIZE / Byte.SIZE);
Sign up to request clarification or add additional context in comments.

Comments

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.