7.25.2014

Integer: bitCount() - Returns the number of one bits in an intger

If you want to get the number of set bits in an integer, you can use the static bitCount() method in java.lang.Integer class by passing the desired integer as argument.

Consider an integer 5 which has binary representation 101. Here, the number of one bits (set bits) is 2. So, bitCount(5) returns 2.

For negative integer it returns the number of one bits in two’s complement representation of that number.

Consider -5 which has two’s complement binary representation 11111111111111111111111111111011. Here, the number of one bits (set bits) is 31. So, bitCount(-5) returns 31.

This method is sometimes referred to as the population count.

Method Declaration:
public static int bitCount(int i)

Live Example:

public class Demo {
    public static void main(String[] args) {
        System.out.println("Number of 1 bits in 2 = " + Integer.bitCount(2)); //2 = 10
        System.out.println("Number of 1 bits in 5 = " + Integer.bitCount(5)); //5 = 101
        System.out.println("Number of 1 bits in 7 = " + Integer.bitCount(7)); //7 = 111
        System.out.println("Number of 1 bits in 15 = " + Integer.bitCount(15)); //15 = 1111
    }  
}

Output: 
Number of 1 bits in 2 = 1
Number of 1 bits in 5 = 2
Number of 1 bits in 7 = 3
Number of 1 bits in 15 = 4


Use the social sharing button below to spread the knowledge among others.

0 comments:

Post a Comment