On this document we will be showing a java example on how to use the bitCount() method of BigInteger Class. Basically this method returns the number of bits in the two’s complement representation of this BigInteger that differ from its sign bit. This method is useful when implementing bit-vector style sets atop BigIntegers.

A quick background on getting the 2’s complement of an integer:

Let’s say we have a decimal number of -24 then in order to get the 2’s complement of this number, write it first in binary.

16  8 4  2 1
 1 1 0 0 0

then we invert it and becomes


and then add 1 because of the negative notation on our integer thus the final result would be:


Now let’s count how many bit’s of the two’s complement of -24, that would be 4 which we get by counting the bits of the result omitting the last digit on the left which is because it is zero.

Method Syntax

public int bitCount()

Method Argument

Data Type Parameter Description

Method Returns

The bitCount() method returns an int value which corresponds to the number of bits in the two’s complement representation of this BigInteger that differ from its sign bit.


Requires Java 1.1 and up

Java BigInteger bitCount() Example

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


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

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

public class IntegerBitCountExample {

	public static void main(String[] args) {	
		// get user input
		System.out.print("Enter the first value:");
		Scanner s = new Scanner(;
		String firstInput = s.nextLine();		

		// convert the first String Input to BigInteger
		BigInteger val1 = new BigInteger(firstInput);
		 * get the the count of bits of the  
		 * user input
		int result = val1.bitCount();
		System.out.println("Bit Count of "+val1+" is "+result);


This example is a lot simpler than it looks. Basically we ask for user input and converted this value into BigInteger. We then printed out the results of the bitCount() operation.

Sample Output

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

BigInteger bitCount() example output