Java Program to shift bits in a BigInteger

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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
raja
Published on 06-Dec-2018 11:31:49
Advertisements