2010-11-09 36 views
3

好的,我對Java很新,所以我很抱歉如果這個問題很愚蠢。在Java中,根據數組大小,如何將字節數組轉換爲特定的基本類型?

我有一個ByteBuffer對象,其中包含的值可能是任意長度的字節數,緩衝區的容量設置爲長度。將緩衝區中的值讀入適當的原始類型的最有效方法是什麼?

下面的代碼是我有問題的代表。

long returnValue; 
ByteBuffer bb = GetBuffer(blah); 

if (bb.capacity() > 4) 
{ 
    returnValue = (long) <how to get value from the buffer here?> 
} 
else if (bb.capacity() > 2) 
{ 
    returnValue = (long) <and here...> 
} 
// etc... 

在異常緩衝結果調用getLong()如果緩衝器的極限是小於8。我想我可以從各個字節構造一個長,但似乎不必要地複雜化。有沒有更好的辦法?

非常感謝!

回答

2

在異常的緩衝效果調用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 
    } 
} 
+0

這很好。謝謝! – Josh 2010-11-09 16:29:53

+0

不客氣:-) – aioobe 2010-11-09 16:34:29

2

ByteBuffer有一些特殊的 「get」 方法,像getLong(int index)

if (bb.capacity() >= 8) 
{ 
    returnValue = bb.getLong(); 
} 
+0

「在一個異常的緩衝效果調用getLong()如果緩衝區的限制小於8」(即,我想他已經知道'getLong') – aioobe 2010-11-09 08:11:18

+0

@aioobe - 啊,是的,你的權利。沒有注意,只是複製了問題中的代碼。 – 2010-11-09 09:04:54

+0

是的。容易做到。我想這個問題是關於如何創建「太少的字節」,儘管他有'if(bb.capacity()> 2) returnValue =(long)'。 (雖然我不是down-voter !!) – aioobe 2010-11-09 09:41:13

相關問題