0
첫 번째 8 바이트는 현재 타임 스탬프 여야하고 나머지 바이트는 그대로 있어야하는 바이트 배열을 만들어야합니다. 그리고 같은 바이트 배열에서 내가 처음에 넣은 타임 스탬프를 추출하고 싶습니다.바이트 배열에서 긴 데이터 형식을 추출하는 방법은 무엇입니까?
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();
}
위의 코드는 예외로, 무엇이 잘못 되었나요? Arrays.copyOfRange
의 문서에서
Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.Buffer.nextGetIndex(Buffer.java:498)
at java.nio.HeapByteBuffer.getLong(HeapByteBuffer.java:406)