如何从字节数组中提取长数据类型?
How to extract long data type from the byte array?
我需要制作一个字节数组,前八个字节应为当前时间戳,其余字节应保持原样。然后我想从同一个字节数组中提取我放在第一位的时间戳。
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();
}
上面的代码给了我异常,我不确定哪里出了问题?
Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.Buffer.nextGetIndex(Buffer.java:498)
at java.nio.HeapByteBuffer.getLong(HeapByteBuffer.java:406)
来自 Arrays.copyOfRange
的文档:
to - the final index of the range to be copied, exclusive. (This index may lie outside the array.)
这意味着,您没有将足够的字节放入缓冲区。
所以正确的做法是:
byte[] newBytes = Arrays.copyOfRange(bytes, 0, Long.SIZE / Byte.SIZE);
我需要制作一个字节数组,前八个字节应为当前时间戳,其余字节应保持原样。然后我想从同一个字节数组中提取我放在第一位的时间戳。
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();
}
上面的代码给了我异常,我不确定哪里出了问题?
Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.Buffer.nextGetIndex(Buffer.java:498)
at java.nio.HeapByteBuffer.getLong(HeapByteBuffer.java:406)
来自 Arrays.copyOfRange
的文档:
to - the final index of the range to be copied, exclusive. (This index may lie outside the array.)
这意味着,您没有将足够的字节放入缓冲区。 所以正确的做法是:
byte[] newBytes = Arrays.copyOfRange(bytes, 0, Long.SIZE / Byte.SIZE);