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?
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.
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.
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 "<<".
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.
You have to capture the bit before the shift:
bool rshift(unsigned int* p) {
bool ret = (*p) & 1;
*p >>= 1;
return ret;
}
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;
}
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With