2016-11-02 62 views
0

我需要制作一个字节数组,使前八个字节应该是当前时间戳,其余字节应该保持原样。然后从同一个字节数组中,我想提取我放在首位的时间戳。如何从字节数组中提取长数据类型?

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) 

回答

2

Arrays.copyOfRange文档:

到 - 的范围内的最后索引被复制,排斥。 (该索引可能位于数组之外。)

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

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