I'm writing a program using bitwise operators in C. It's for a school assignment and the objective is to count the number of 1's in the bit representation of an integer, then print "Even" if the result is even and "Odd" if it's odd.
I wrote a program to loop through each bit and compare the inputted integer with a mask and increment a counter variable for each time the bitwise AND operator returns 1. However, the program doesn't seem to be incrementing the counter variable. Here's the code:
#include <stdio.h>
void bitsEvenOrOdd(int value);
int main(void) {
int integer;
printf("Enter an integer: ");
scanf("%d", &integer);
bitsEvenOrOdd(integer);
return 0;
}
void bitsEvenOrOdd(int value) {
unsigned int displayMask;
unsigned int i;
unsigned int counter;
counter = 0;
displayMask = 1 << 31;
for (i = 0; i < 32; i++) {
if ((value & displayMask) == 1) {
counter++;
}
value <<= 1;
}
if ((counter % 2) == 0) {
printf("The total number of 1's in the bit representation is even.\n");
}
else {
printf("The total number of 1's in the bit representation is odd.\n");
}
}
Any words of advice or tips are greatly appreciated. Thank you!