C. Rib
C. Rib

Reputation: 390

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;
}

Upvotes: 1

Views: 2523

Answers (2)

Charlie Martin
Charlie Martin

Reputation: 112356

>> is an operator like any other. x = x>>1; will do it, which of course means x>>=1 will do it.

Update

if you want to divide by 2 you should indeed shift by 1.

Don't make fun of me, I'm old.

Upvotes: 0

Brick
Brick

Reputation: 4262

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.

Upvotes: 1

Related Questions