Set a bit for BigInteger in Java


The setBit() method is used in Java to return a BigInteger whose value is equivalent to this BigInteger with the designated bit set.

Example

 Live Demo

import java.math.*;
public class BigIntegerDemo {
   public static void main(String[] args) {
      BigInteger one, two;
      one = new BigInteger("7");
      two = one.setBit(3);
      System.out.println("Result: " +two);
   }
}

Output

Result: 15

Let us see another example.

Example

 Live Demo

import java.math.*;
public class Demo {
   public static void main(String[] args) {
      BigInteger bi1, bi2;
      bi1 = new BigInteger("9");
      // setbit operation using index 3
      bi2 = bi1.setBit(3);
      String res = "Setbit operation on " +bi1+ " at index 3 gives " +bi2;
      System.out.println(res);
   }
}

Output

Setbit operation on 9 at index 3 gives 9

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 25-Jun-2020

127 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements