2011-11-10 40 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

它可以很容易。 –