Current Location: Home> Latest Articles> How to Calculate the Number of Set Bits in an Integer Using PHP

How to Calculate the Number of Set Bits in an Integer Using PHP

gitbox 2025-06-15

Introduction

In computer science, it is often necessary to calculate the number of set bits in a binary number. This is useful in many areas, such as cryptography, encoding, and computer security. In this article, we will show how to write a PHP program to calculate the number of set bits in an integer.

Binary Numbers

Before we calculate the bit count, it's important to understand binary numbers. Binary numbers consist only of the characters "0" and "1". Each digit represents a different power of 2. For example, the decimal number 5 is represented in binary as 101. This means: $1*2^2 + 0*2^1 + 1*2^0 = 5$.

Set Bits

Each bit with a value of 1 in a number is called a "set bit". What we need to calculate is how many such set bits exist in an integer.

Program Design

Although calculating the number of set bits is not a difficult task, we need to use an efficient algorithm that works correctly. Below, we will write a PHP function to achieve this.


function countSetBits($num) {
    $count = 0;
    while ($num > 0) {
        $count += $num & 1;
        $num >>= 1;
    }
    return $count;
}

This function uses bitwise operations to directly manipulate each bit of the number. By looping through the bits, the counter increments whenever the bit is set to 1.

Explanation

"Bitwise operations" refer to mathematical operations performed on binary numbers. In PHP, we can use operators such as "&", "|", "^", "~", "<<", and ">>".

In our function, we use the "&" and ">>" operators:

1. The "&" operator compares the binary representation of the number with another value (in this case, 1). If the set bit equals 1, the counter is incremented.

2. The ">>" operator shifts the number right by one bit, moving the remaining bits to the left to prepare for comparison of the next bit.

Running the Program

Here is the code to test the function and output the result:


$num = 15;
$bits = countSetBits($num);
echo "Number of set bits in " . $num . " is " . $bits;

The output of the above code should be:

Number of set bits in 15 is 4

Conclusion

Writing a PHP program to calculate the number of set bits in a number is not difficult. By using bitwise operations, we can compare the value of each bit in the binary representation of the number and compute the total number of set bits. Mastering this technique not only helps you understand the fundamentals of computer hardware but also has practical applications in areas like cryptography and encoding.