2

Let's say I have some 32 bit integer:

000001010100010000100010001001 1 0

(The penultimate bit is bold/italic)

So if I shift it by 2 to the right I get:

00000001010100010000100010001001

Now the penultimate bit is lost. I thought of storing the original value and then using || (logical OR), but that would only work if the penultimate bit is set to 1. What if it's 0?

2
  • 1
    possible duplicate of How do you set, clear and toggle a single bit in C/C++? Commented Aug 21, 2014 at 16:21
  • I don't understand the question at all. Obviously, if you shift a value, all of the bits you shift out are lost; that's the definition of shifting. So what are you trying to do? If you want to save the next to the last bit, you need to save it before shifting (or save the last bit after having shifted n-1). Commented Aug 21, 2014 at 16:47

3 Answers 3

9

You'd want bitwise, not logical or; and to preserve the value, you'd need to clear the bit in the new value before inserting the one from the old value:

uint32_t const shift = 2; // number of bits to shift by uint32_t const mask = (1 << 1); // set of bits to preserve uint32_t bit_to_save = value & mask; value >>= shift; value &= ~mask; value |= bit_to_save; 

or, if you like brevity:

value = ((value >> shift) & ~mask) | (value & mask); 
Sign up to request clarification or add additional context in comments.

6 Comments

But how on earth did his question make you think that this is what he was trying to do?
@JamesKanze: Basic reading comprehension. This shifts the bits without changing one of them, exactly as the question describes.
Well, I still can't figure it out from what he wrote.
And you might add something concerning the relationship between mask and shift.
@JamesKanze: There's no relationship. One's the number of bits to shift by; the other's the mask of bits to preserve. But I'll add comments in case anyone else can't guess the meaning from the names.
|
4

Use bitwise operations:

(x>>2) & ~2 | (x&2) 

x>>2 shifts right by 2.

& ~2 sets the penultimate bit to 0

| (x&2) 'grafts' in the penultimate bit from the original number.

Comments

0
int x;//whatever int penultimate_shift=(x&0x2)|((x>>2)&~0x2); 

2 Comments

Would you be able to provide a bit more detail as to what is going on here?
x&0x2 selects the "panultimate" bit, x>>2 is the bit shift, the result of that is reset, and then the or sets it to the panultimate bit

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.