QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Bit Counting

Counts the set bits in the binary representation of an integer

  • math
  • number
  • bits
  • bit-counting

Code

public static int countBits(int number) {
    int bits = 0;
        
    while (number > 0) {
        bits += number & 1;
        number >>= 1;
    }

    return bits;
}

Usage

int number = 5;
System.out.println(countBits(5)); // 2 (101)