Your task is to count the number of 1 bits in the binary representation of a number.
Restrictions
Keep your hands off that bit-count functionality provided by your standard library! Solve this one yourself using other basic tools instead.
But how can I check if for example how many 1 there are in the number 5 without using bit operations ?
Re-read your assignment. It doesn't say you can't use bit operations. It says you cant use the "bit-count functionality provided by your standard library". Look into the C++ Bitwise Operators.
Maybe use the right shift operator in a loop and see what is in bit position 0 each time. Unsigned integers work best with bit shifts. Negative numbers are more tricky.
We can count the number of set bits (1s) in the binary representation of a number without using any built-in bit-counting functions. A common and efficient way to do this is using Brian Kernighan's Algorithm .
The idea is to repeatedly turn off the rightmost set bit of the number until the number becomes 0. Each time we turn off a bit, we increment a counter. The operation n & (n - 1) clears the least significant set bit of n .
n & (n - 1) => 0100 & 0011 => 0000 (n becomes 0, count = 2)
The loop stops. The count is 2, which is correct for the number 6.
#include <iostream>
// Function to count set bits using Brian Kernighan's Algorithm
int countSetBits(int n) {
int count = 0;
while (n > 0) {
n = n & (n - 1); // Clear the least significant set bit
count++;
}
return count;
}
void setup() {
Serial.begin(115200);
uint32_t num = 65535; // number to test
int cnt = 0; // 1's counter
while (num > 0) {
if (num % 2 == 1) cnt++;
num /= 2; // short form of num = num / 2
}
Serial.println(cnt);
}
void loop() {
}
Since the OP has already been handed a ready made solution, I feel it will not be doing any harm to add yet another one and, anyway, I guess his professor will being seeing a stack of similar AI generated solutions.
Here I used Deep Seek to produce a solution based on a recursive lambda function which should distinguish it from the other solutions that will be provided. It looks plausible enough but I've not tested it.