Java.math.BigInteger.testBit()方法範例


java.math.BigInteger.testBit(int n) 當且僅當所指定的位被置位時返回true。它計算方式為 (this & (1<<n)) != 0).

宣告

以下是java.math.BigInteger.testBit()方法的宣告

public boolean testBit(int n)

引數

  • n - 位的指數測試

返回值

此方法返回當且僅當此BigInteger的指定位被設定為true。

異常

  • ArithmeticException - n 是一個負數

例子

下面的例子顯示math.BigInteger.testBit()方法的用法

package com.yiibai;

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