Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 742
Svad Histhana Avatar asked Feb 27 '12 08:02

Svad Histhana


People also ask

How do you calculate bit shift?

To calculate a left shift by 3 bits, follow these steps: Get your number in a binary format, e.g., 0000 0101 . Shift your bit string 3 positions to the left, discarding the digits falling out of scope, and filling up from the right with 0's: 0010 1000 . And that's it; you performed a shift of 3 bits to the left.

What does bit shifting by 1 do?

Bitshifting shifts the binary representation of each pixel to the left or to the right by a pre-defined number of positions. Shifting a binary number by one bit is equivalent to multiplying (when shifting to the left) or dividing (when shifting to the right) the number by 2.

How do you shift left bits?

When shifting left, the most-significant bit is lost, and a 0 bit is inserted on the other end. The left shift operator is usually written as "<<".

What happens when you shift bits?

Logical bit shifting may be useful for multiplying or dividing unsigned integers by powers of two. For example, if the value "0001" or "1" is shifted left, it becomes "0010" or "2," shifted to the left again it becomes "0100," or "4." Shifting to the right has an opposite effect of dividing the value by two per shift.


3 Answers

You have to capture the bit before the shift:

bool rshift(unsigned int* p) {
    bool ret = (*p) & 1;
    *p >>= 1;
    return ret;
}
like image 197
NPE Avatar answered Oct 01 '22 17:10

NPE


To do this for any shift, and any type, reverse the operation (to check whether you lost something).

template <typename T> bool rshift(T& val) {
  T const original = val;
  return ((val >>= 1) << 1) != original;
}
template <typename T> bool lshift(T& val) {
  T const original = val;
  return ((val <<= 1) >> 1) != original;
}
like image 26
bitmask Avatar answered Oct 01 '22 16:10

bitmask


You don't. You have to test it before the shift:

bool
rshift( unsigned& i )
{
    bool results = (i & 0x01) != 0;
    i >>= 1;
    return results;
}

(This is simple for a right shift. For a left shift, you have to know the number of bits in the word.)

like image 35
James Kanze Avatar answered Oct 01 '22 17:10

James Kanze