C. Rib C. Rib - 1 month ago 7
C Question

How do I store the shifted bit in a bitwise operation in C?

I was trying to make a simple function to check how many bits set to 1 were in an int.

What I achieved at first was

#include <stdio.h>

int bitsOne (int x){
int r=0;
while (x > 0){
if (x % 2 == 1) r++;
x = x/2;
}
return r;
}


I was trying to use the
>>
operator for this instead but I don't know how I can store the shifted number.




Update

Using Brick's suggestion I achieved what I wanted,

#include <stdio.h>

int bitsOne (int x){
int r=0;
int bit;
while (x > 0){
bit = (x & 1);
if (bit == 1) r++;
x>>=1;
}
return r;
}

Answer

Get the bit in the last slot before you do the shift using a mask:

int bit = (x & 1);

Then do the shift on x.

Comments