天天看點

BigInteger.testBit(int n)與setBit(int n)

1、jdk7文檔解釋

  • public boolean testBit(int n)      
    Returns

    true

    if and only if the designated bit is set. (Computes

    ((this & (1<<n)) != 0)

    .)
    Parameters:

    n

    - index of bit to test.
    Returns:

    true

    if and only if the designated bit is set.
    Throws:

    ArithmeticException

    -

    n

    is negative.

翻譯:

   當且僅當指定的位被設定時傳回true。

是不是 還是不清楚????下面将解釋解釋清楚

2、代碼

public class TestBit {

	public static void main(String[] args) {
		BigInteger bi = new BigInteger("12"); 
		
		//testBit 的判斷條件為((this & (1<<n)) != 0 
		System.err.println("Test Bit on " + bi + " at index 1 returns  "+bi.testBit(1));
		System.err.println("Test Bit on " + bi + " at index 2 returns  "+bi.testBit(2));
		System.err.println("Test Bit on " + bi + " at index 3 returns  "+bi.testBit(3));
		System.err.println("Test Bit on " + bi + " at index 4 returns  "+bi.testBit(4));
		//12 的二進制表示為1100
		//1    的二進制表示為0001  ,1<<1 為00000010,  (this & (1<<1))為0,bi.testBit(1)為FALSE
		//2    的二進制表示為0010  ,1<<2 為00000100,  (this & (1<<2))為4,bi.testBit(2)為true
		//3    的二進制表示為0011  ,1<<3 為00001000,  (this & (1<<3))為8,bi.testBit(3)為true
		//4    的二進制表示為0100  ,1<<4 為00010000,  (this & (1<<4))為0,bi.testBit(4)為FALSE
	}

}
           

結果

BigInteger.testBit(int n)與setBit(int n)

Test Bit on 12 at index 0 returns   FALSE

因為1<<0  還是1。

3、java基礎解釋

& 既是位運算符又是邏輯運算符,&的兩側可以是int,也可以是boolean表達式,當&兩側是int時,要先把運算符兩側的數轉化為二進制數再進行運算。      
①12&5 的值是多少?答:12轉成二進制數是1100(前四位省略了),5轉成二進制數是0101,則運算後的結果為0100即4  這是兩側為數值時;      
② 若 int  i = 2,j = 4;則(++i=2)&(j++=4)的結果為false,其過程是這樣的:先判斷++i=2是否成立,這裡當然是不成立了(3 == 2),但是程式還會繼續判斷下一個表達式是否成立,j++=4 ,該表達式是成立的,但是&運算符要求運算符兩側的值都為真,結果才為真,是以(++i=2)&(j++=4)的結果為 false       

<<    移位運算符 就是在二進制的基礎上對數字進行平移。按照平移的方向和填充數字的規則分為三種:<<(左移)、>>(帶符号右移)和>>>(無符号右移)。

比如

3 << 2   過程是0011 ----》  1100      

4、

上面代碼中已經解釋了

//12 的二進制表示為1100

//1    的二進制表示為0001  ,1<<1 為00000010,  (this & (1<<1))為0,bi.testBit(1)為FALSE

//2    的二進制表示為0010  ,1<<2 為00000100,  (this & (1<<2))為4,bi.testBit(2)為true

//3    的二進制表示為0011  ,1<<3 為00001000,  (this & (1<<3))為8,bi.testBit(3)為true

//4    的二進制表示為0100  ,1<<4 為00010000,  (this & (1<<4))為0,bi.testBit(4)為FALSE

這裡說一下&,當1100&0010時,二進制每一位上的數與操作,都為1時得1,其他情況為0,是以1100&0010為0000

5、

BigInteger bi = new BigInteger("12"); 
		
		bi =bi.setBit(2);
		bi =bi.setBit(4);
           

bi的值将是12+2^5 =28

jdk解釋:

  • public BigInteger setBit(int n)      
    Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit set. 
  • (Computes

    (this | (1<<n))

    .)

12的二進制為00001100,

12|(1<<2)為1100|0100=1100,是以12|(1<<2)為12

12|(1<<4)為1100|0001000=00011100,12|(1<<4)為28

6、下節将解釋利用BigInteger.testBit(int n)與setBit(int n)來進行權限判斷

http://blog.csdn.net/u014520797/article/details/64442728