Reputation: 3450
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!
Upvotes: 2
Views: 5339
Reputation: 64
You should be checking the lowest bit to fix the issue. Consider the below change in your code
unsigned int counter;
counter = 0;
- displayMask = 1 << 31;
+ displayMask = 1;
for (i = 0; i < 32; i++) {
if ((value & displayMask) == 1) {
counter++;
}
- value <<= 1;
+ value >>= 1;
}
if ((counter % 2) == 0) {
Upvotes: 0
Reputation: 20402
if ((value & displayMask) == 1) {
Consider this operation. displayMask
is 0x80000000. Bitwise and between that number and any other number can only be 0x80000000 or 0. You're comparing it to 1.
Either compare if it's not equal to 0 or (I would recommend this), check the lowest bit set and shift right instead of left.
Upvotes: 3
Reputation: 6404
Look at the line
if( (value & displayMask) == 1)
and consider what happens when displayMask is 2, 4, 8 etc
Upvotes: 0
Reputation: 225817
You're shifting the wrong way:
value >>= 1;
Assuming an int
is 32-bit, displayMask = 1 << 31
sets the highest order but in displayMask
. When you left shift that value by 1, the single set bit gets shifted out, so your mask is now 0.
Change to a right shift.
value >>= 1;
Your comparison is also incorrect:
if ((value & displayMask) == 1) {
This will be true only if the mask is 1 and the low order bit is set. Instead, check if the result is nonzero:
if ((value & displayMask) != 0) {
Upvotes: 0