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


java.math.BigInteger.shiftRight(int n) 返回一個BigInteger,其值為(this>> n)的。符號擴充套件執行。移位距離,正,可能為負,在這種情況下,這個方法執行左移。它計算方法為 floor(this / 2n).

宣告

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

public BigInteger shiftRight(int n)

引數

  • n - 移動距離,以位元位形式。

返回值

該方法返回一個BigInteger物件的值是 this >> n .

異常

  • ArithmeticException - 如果移位距離為 Integer.MIN_VALUE

例子

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

package com.yiibai;

import java.math.*;

public class BigIntegerDemo {

public static void main(String[] args) {

	// create 3 BigInteger objects
	BigInteger bi1, bi2, bi3;

	bi1 = new BigInteger("4");

	// perform right shift operation on bi1 using 2 and -2
	bi2 = bi1.shiftRight(2);
	bi3 = bi1.shiftRight(-2);

	String str1 = "Right shift on " +bi1+ ", 2 times gives " +bi2;
	String str2 = "Right shift on " +bi1+ ", -2 times gives " +bi3;

	// print bi2, bi3 values
	System.out.println( str1 );
	System.out.println( str2 );
   }
}

讓我們編譯和執行上面的程式,這將產生以下結果:

Right shift on 4, 2 times gives 1
Right shift on 4, -2 times gives 16