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

 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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 25-Jun-2020

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements