java.math.BigInteger shiftRight(int n)
Description
Let’s take a for example a BigInteger 12 which is equivalent to binary 1100. So if we have a value n=1, then the binary 1100 shifted to the right by 1 would become 110. The equivalent of 110 is 12 which be the returned value of the method shiftRight().
Notes:
- this method is related to shiftLeft().
Method Syntax
public BigInteger shiftRight(int n)
Method Argument
| Data Type | Parameter | Description |
|---|---|---|
| int | n | index of bit to shift. |
Method Returns
The flipBit() method this >> n
Compatibility
Requires Java 1.1 and up
Java BigInteger shiftRight(int n) Example
Below is a java code demonstrates the use of shiftRight(int n) method of BigInteger class. The example presented might be simple however it shows the behavior of the shiftRight(int n) method.
package com.javatutorialhq.java.examples;
import java.math.BigInteger;
import java.util.Scanner;
/*
* A java example source code to demonstrate
* the use of shiftRight(int n) method of BigInteger class
*/
public class BigIntegerShiftRightExample {
public static void main(String[] args) {
// initialize a BigInteger object
BigInteger val1 = new BigInteger("12");
/*
* Note: 17 in binary is 10001
*/
// get user input
System.out.print("Enter the shift distance:");
Scanner s = new Scanner(System.in);
String input = s.nextLine();
s.close();
/*
* convert the input to Integer unboxing feature will be used to
* transform Integer to primitive int
*/
Integer inputBitNumber = Integer.parseInt(input);
// get the new BigInteger result after shifting to the right
BigInteger result = val1.shiftRight(inputBitNumber);
System.out.println("Result of the operation:" + result);
}
}
This example is a lot simpler than it looks. The first part is the declaration of a BigInteger. User are then asked to provide the shift distance. We then shifted the BigInteger object to the right with the specified shift distance. Result is printed at the end.
