stillAFanOfTheSimpsons
stillAFanOfTheSimpsons

Reputation: 173

Shift bit-wise operation

I'm learning c programming and now struggling with the bit-wise operation. Say if I want to shift short n >> by 4 and << by 10, and use the short result as the condition of a loop. i.e if (result==1) {//do something} do I need to declare another two variables, i.e. short right= n>>4; short left=... or is there a more proper way of writing this? Thanks!

Upvotes: 1

Views: 109

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598134

You do not need additional variables unless you intend to use the result of the shifts more than once.

Shifting right by 4 and then left by 10 is not the same as just shifting left by 6, so you have to do separate shifts if you want the side effect of shifting past the end of the right side to zero out some of the right-hand bits, eg:

short n = ...;
if (((n >> 4) << 10) == 1) {
    //do something
}

Let's say you start with 0xFFFF (1111111111111111). Shifting right by 4 produces 0x0FFF (0000111111111111), then shifting that left by 10 produces 0xFC00 (1111110000000000).

On the other hand, if you just shift left by 6:

short n = ...;
if ((n << 6) == 1) {
    //do something
}

0xFFFF becomes 0xFFC0 (1111111111000000) instead. Clearly not the same value.

So you have to be careful with your shifts.

BTW, shifting by these particular values will never produce a result of 1.

Upvotes: 3

Related Questions