java.math.BigInteger setBit(int n)

Description

On this document we will be showing a java example on how to use the setBit(int n) method of BigInteger Class. Basically this method returns a BigInteger whose value is equivalent to this BigInteger with the designated bit set. (Computes (this | (1<<n)).)

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 equivalent would become 1110 after using the method setBit(int n). Remember that the counting starts 0 index. Binary 1110 is equal to 14 in BigInteger so that would be the returned value.

Notes:

  • this method throws an Arithmetic exception if n supplied is negative.

Method Syntax

public BigInteger setBit(int n)

Method Argument

Data Type Parameter Description
int n index of bit to set.

Method Returns

The flipBit() method this ^ (1<<n)

Compatibility

Requires Java 1.1 and up

Java BigInteger setBit(int n) Example

Below is a java code demonstrates the use of flipBit() method of BigInteger class. The example presented might be simple however it shows the behavior of the flipBit() method.

package com.javatutorialhq.java.examples;

import java.math.BigInteger;
import java.util.Scanner;

/*
 * A java example source code to demonstrate
 * the use of setBit(int n) method of BigInteger class
 */

public class BigIntegerSetBitExample {

	public static void main(String[] args) {

		// initialize a BigInteger object
		BigInteger val1 = new BigInteger("17");
		/*
		 * Note: 17 in binary is 10001
		 */

		// get user input
		System.out.print("Enter the bit number you want to set:");
		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
		BigInteger result = val1.setBit(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 index of bit to be set. When we say bit flipping is that we set the bit on the specified index to 1. Using the initially declared BigInteger and the index provided by the user, we will be simulating the behavior of the setBit() method.

Sample Output

Below is the sample output when you run the above example.

BigInteger setBit() example output