在異常的緩衝效果調用getLong()如果緩衝區的限制是小於8
這是因爲長是 8個字節。見Primitive Data Types。
如果你想創建一個任意長度的字節,我建議你通過插入零來填充並使用getLong()
。 (請參閱下面的示例。)
如果要在精確的4個字節中創建long
,則可以執行一些操作,如(long) bb.getInt()
。
最後,除非您使用ByteBuffer.remaining()
而不是ByteBuffer.capacity()
我建議您使用絕對獲取方法長時間:ByteBuffer.getLong(0)
。
我想我可以從單個字節構造一個long,但這似乎不必要的複雜。有沒有更好的辦法?
是的,還有更好的辦法。下面是一個例子程序,它應該讓你開始:
import java.nio.ByteBuffer;
public class Main {
static ByteBuffer longBuf = ByteBuffer.allocate(8);
public static long getLong(ByteBuffer bb) {
// Fill with eight 0-bytes and set position.
longBuf.putLong(0, 0).position(8 - bb.remaining());
// Put the remaining bytes from bb, and get the resulting long.
return longBuf.put(bb).getLong(0);
}
public static void main(String[] args) {
ByteBuffer bb = ByteBuffer.allocate(10);
// Add 2 bytes
bb.put((byte) 5);
bb.put((byte) 7);
// Prepare to read
bb.flip();
long l = getLong(bb);
System.out.println(Long.toBinaryString(l)); // Prints 10100000111
// Correct since, 00000101 00000111
// |--------|--------|
// 5 7
}
}
這很好。謝謝! – Josh 2010-11-09 16:29:53
不客氣:-) – aioobe 2010-11-09 16:34:29