2011-11-10 71 views
2

我想比較Java中使用大數字移位操作實現的兩個乘法方法。因此我需要足夠大的BigIntegers。獲取n位BigInteger的最大值

因爲我想按位比較它們,最好的辦法是用乘法運算中完全使用的n位來產生BigInteger。

我的做法,到目前爲止是這樣的:

byte[] bits = new byte[bitLength]; 

BigInteger number = new BigInteger(bits).flipBit(bitLength); 

回答

2

如何:

import java.math.BigInteger; 

public class Test 
{ 
    public static void main(String[] args) 
    { 
     int bits = 3; 

     BigInteger value = BigInteger.ZERO 
            .setBit(bits) 
            .subtract(BigInteger.ONE); 
     System.out.println(value); // Prints 7 == 111 in binary 
    } 
} 

換句話說,設置該位是一個更高不是你想要的,然後再減去一個得到一個使用所有較低位的值。

+0

它可以很容易。 –