Print the Count
In this final step, we'll enhance our bit counting program to provide more detailed output and demonstrate different ways of printing the set bit count.
Let's modify the bit_counter.c
file to add more comprehensive printing:
cd ~/project
nano bit_counter.c
Update the code with the following implementation:
#include <stdio.h>
// Function to count set bits using bitwise AND operation
int countSetBits(int number) {
int count = 0;
while (number) {
count += number & 1;
number >>= 1;
}
return count;
}
int main() {
int number;
// Prompt the user to enter an integer
printf("Enter an integer: ");
scanf("%d", &number);
// Count the number of set bits
int setBitCount = countSetBits(number);
// Print the count in multiple formats
printf("Decimal Number: %d\n", number);
printf("Binary Representation: ");
// Print binary representation
for (int i = 31; i >= 0; i--) {
int bit = (number >> i) & 1;
printf("%d", bit);
}
printf("\n");
// Print set bit count results
printf("Number of Set Bits: %d\n", setBitCount);
printf("Set Bit Percentage: %.2f%%\n",
(float)setBitCount / 32 * 100);
return 0;
}
Compile and run the program:
gcc bit_counter.c -o bit_counter
./bit_counter
Example output:
Enter an integer: 42
Decimal Number: 42
Binary Representation: 00000000000000000000000000101010
Number of Set Bits: 3
Set Bit Percentage: 9.38%
Code Explanation:
- Added binary representation printing
- Included percentage calculation of set bits
- Used bitwise operations to extract individual bits
- Formatted output to provide multiple perspectives on bit count
The program now offers a comprehensive view of the integer's bit composition, showing:
- Decimal value
- Full 32-bit binary representation
- Total number of set bits
- Percentage of set bits