繁体   English   中英

如何从字节数组中提取长数据类型?

[英]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-要复制的范围的最终索引(不包括)。 (此索引可能位于数组之外。)

这意味着您没有将足够的字节放入缓冲区。 因此,正确的方法是:

byte[] newBytes = Arrays.copyOfRange(bytes, 0, Long.SIZE / Byte.SIZE);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM