Search code examples
c++visual-c++bit-manipulation

How do I get the "lost" bit from a bit shift?


I want to bit shift a variable and store the bit that's shifted out in a boolean.

Something like:

unsigned int i = 1;
bool b = rshift(&i); // i now equals 0 and b is set to true

How can this be accomplished?


Solution

  • You have to capture the bit before the shift:

    bool rshift(unsigned int* p) {
        bool ret = (*p) & 1;
        *p >>= 1;
        return ret;
    }