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  

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值