Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Java Program to shift bits in a BigInteger
To shift bits in a BigInteger, use the shiftLeft() or shiftRight() method.
shiftLeft() method
The java.math.BigInteger.shiftLeft(int n) returns a BigInteger whose value is (this << n). The shift distance, n, may be negative, in which case this method performs a right shift. It computes floor(this * 2n).
Example
import java.math.*;
public class Demo {
public static void main(String[] args) {
BigInteger one;
one = new BigInteger("15");
one = one.shiftLeft(2);
System.out.println("Result: " +one);
}
}
Output
Result: 60
shiftRight() method
The java.math.BigInteger.shiftRight(int n) returns a BigInteger whose value is (this >> n). Sign extension is performed. The shift distance, n, may be negative, in which case this method performs a left shift. It computes floor(this / 2n).
Example
import java.math.*;
public class Demo {
public static void main(String[] args) {
BigInteger one;
one = new BigInteger("25");
one = one.shiftRight(3);
System.out.println("Result: " +one);
}
}
Output
Result: 3
Advertisements
