java.math.BigInteger getLowestSetBit()

Description

On this document we will be showing a java example on how to use the getLowestSetBit() method of BigInteger Class. Basically this method Returns the index of the rightmost (lowest-order) one bit in this BigInteger (the number of zero bits to the right of the rightmost one bit). Returns -1 if this BigInteger contains no one bits. (Computes (this == 0? -1 : log2(this & -this)).)

To better illustrate the use of this method lets take for example, lets say we have a number 24 the equivalent of this number in binary would be 11000. As the description of the getLowestSetBit, this method will return the index where 1 can be found starting from right going to left. So the binary 11000, the first one-bit would be index 3. Remember that you should start counting from 0. Most programmers make a mistake on this, so please take note of this rule that counting starts at 0.

Method Syntax

public int getLowestSetBit()

Method Argument

Data Type Parameter Description
N/A N/A N/A

Method Returns

The getLowestSetBit() method returns an int primitive which corresponds to the index of the rightmost one bit in this BigInteger.

Compatibility

Requires Java 1.1 and up

Java BigInteger getLowestSetBit() Example

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

package com.javatutorialhq.java.examples;

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

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

public class BigIntegerGetLowestSetBitExample {

	public static void main(String[] args) {

		// get user input
		System.out.print("Enter a number:");
		Scanner s = new Scanner(System.in);
		String input = s.nextLine();
		s.close();

		/*
		 * convert the input to BigInteger
		 */

		BigInteger val1 = new BigInteger(input);

		// get the new BigInteger
		int result = val1.getLowestSetBit();
		System.out.println("Result of the operation:" + result);

	}

}

This example is a lot simpler than it looks. We simply ask for userInput. Since the user input were in String format, we have used one of the constructor of BigInteger class to convert the string input to BigInteger. This translated input then evaluated using the getLowestSetBit() method to determine the lowest bit that has been set to 1.

Sample Output

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

BigInteger getLowestSetBit() example output