2012-03-15 65 views
1

我知道有一個缺少強制轉換爲長轉移,但有一個更好的方式來做到這一點比所示計算策略減少混亂。32位的int由量不在範圍

static long getLong(byte[] sourceBytes, int sourceBytesIndex, int numOfBytesToConvert) 
{ 
    long longValue = 0; 

    longValue = (sourceBytes[sourceBytesIndex] & 0xFF) + 
         ((sourceBytes[sourceBytesIndex + 1] & 0xFF) << 8); 

    if (numOfBytesToConvert > 2) 
    { 
     longValue += ((sourceBytes[sourceBytesIndex + 2] & 0xFF) << 16) + 
           ((sourceBytes[sourceBytesIndex + 3] & 0xFF) << 24); 

     if (numOfBytesToConvert > 4) 
     { 
      longValue += ((sourceBytes[sourceBytesIndex + 4] & 0xFF) << 32) + 
            ((sourceBytes[sourceBytesIndex + 5] & 0xFF) << 40); 

      if (numOfBytesToConvert > 6) 
      { 
       longValue += ((sourceBytes[sourceBytesIndex + 6] & 0xFF) << 48) + 
             ((sourceBytes[sourceBytesIndex + 7] & 0xFF) << 56); 
      } 
     } 
    } 

    return longValue; 
} 
+1

怎麼樣一個簡單的循環? – Voo 2012-03-15 10:59:07

+0

順便說一句:使用'&0xFFL'而不是'&0xFF'會給你'長'值。 – 2012-03-15 11:19:44

回答

4

我寧願使用ByteBuffers,也可以使用switch語句。

static long getLong(ByteBuffer bb, int numOfBytesToConvert) { 
    switch (numOfBytesToConvert) { 
     case 8: 
      return bb.getLong(); 
     case 6: 
      long aChar = bb.getChar(); 
      long anInt = bb.getInt() & 0xFFFFFFFFL; 
      return bb.order() == ByteOrder.LITTLE_ENDIAN 
        ? aChar << 32 + anInt 
        : anInt << 16 + aChar; 
     case 4: 
      return bb.getInt() & 0xFFFFFFFFL; 
     case 2: 
      return bb.getChar(); 
     default: 
      throw new IllegalArgumentException(); 
    } 
} 

ByteBuffer同時處理字節字節以及緩衝區中可用字節的位置和結尾。 (使用極限())

我傾向於選擇直接的ByteBuffers,因爲在使用本地字節順序時,可能會有很大的堆而沒有使用太多的堆並且速度比byte[]更快。

+0

Thx,提供豐富的答案和智能解決方案。 – arge 2012-03-15 12:10:35

1

該做的伎倆:

long value = new BigInteger(sourceBytes).longValue(); 

static long getLong(byte[] sourceBytes, int sourceBytesIndex, int numOfBytesToConvert) { 
    byte[] bytes = new byte[numOfBytesToConvert]; 
    System.arraycopy(sourceBytes, sourceBytesIndex, bytes, 0, numOfBytesToConvert); 
    return new BigInteger(sourceBytes).longValue(); 
} 
+0

我懷疑'sourceBytesIndex'和'numOfBytesToConvert'很重要。 ;) – 2012-03-15 11:10:15

+0

我記得,我曾經聽說過一個'System.arraycopy'函數。如果仍然存在(它很老了),那麼它可以幫助;) – 2012-03-15 11:13:08

+0

隨着創建一個新的byte [],它可以幫助,但BigInteger的只需要一個字節順序,大端,所以循環可能是更好的選擇。 (;的例子是小端;) – 2012-03-15 11:16:12