2016-11-02 4 views
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) 

답변

2

님의

- 범위의 마지막 인덱스, 독점 복사합니다. 이 색인은 배열 외부에있을 수 있습니다.

즉, 버퍼에 충분한 바이트를 넣지 않았습니다. 올바른 방법은 다음과 같습니다.

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