Java.math.BigInteger.testBit()方法实例 权限设置


import java.math.BigInteger;  
  
public class TestBigInteger {  
  
    public static void main(String[] args) {  
        //初始  
        BigInteger num = new BigInteger("0");  
        num = num.setBit(2);  
        num = num.setBit(1);  
        System.out.println(num);  
        System.out.println(num.testBit(2));  
        System.out.println(num.testBit(1));  
        System.out.println(num.testBit(3));  
    }  
  
}  

返回的结果是:

6
true
true
false

为什么是6呢? 6= 2^2 + 2^1 其实计算的值是2的权的和

 



import java.math.*;

public class BigIntegerDemo {

public static void main(String[] args) {

	// create a BigInteger object
	BigInteger bi;

	// create 2 boolean objects
	Boolean b1, b2;

	bi = new BigInteger("10"); 

	// perform testbit on bi at index 2 and 3
	b1 = bi.testBit(2);
	b2 = bi.testBit(3);

	String str1 = "Test Bit on " + bi + " at index 2 returns " +b1;
	String str2 = "Test Bit on " + bi + " at index 3 returns " +b2;

	// print b1, b2 values
	System.out.println( str1 );
	System.out.println( str2 );
   }
}

让我们编译和运行上面的程序,这将产生以下结果:

Test Bit on 10 at index 2 returns false
Test Bit on 10 at index 3 returns true
  java.math.BigInteger.testBit(int n)  当且仅当所指定的位被置位时返回true。它计算方式为 (this & (1<<n)) != 0).

总结一下:

& 是比较位的, 两个都位1 , 则保留,

1<<2   = 4       二进制(100)    100 & 1010  = 0 

1<<3  =8   二进制(1000)  1000& 1010 = 8  



猜你喜欢

转载自blog.csdn.net/qq_30285985/article/details/53923805