2012-03-15 62 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