I am working on bit shifts, and I’ve run into this problem.
I have two int:
int x = 1;
int y = 2;
What is the difference between:
x = x << (31 + 1);
and
y = y << 31;
I thought the result would be the same (namely that x and y would both equal 1) , but they aren’t…..I don’t understand why. 2 is just 1 with a “1” bit moved one space to the left.
Thanks!
I mean when we can’t shift-left anymore, don’t we wrap around to the beginning?
EDIT:
Let me clarify what I THINK is going on:
We start with x = 1, so that’s:
00000000 00000000 00000000 00000001
We then left shift that by 31 +1 (or 32). That gives us:
00000000 00000000 00000000 00000001
which is also 1.
Then we do y = 2, so that’s
00000000 00000000 00000000 00000010
We left shift that by 31. That also gives us:
00000000 00000000 00000000 00000001
Therefore, we get x = y = 1. I know this is wrong, but can anyone explain why???
You are confusing shifting with rotating:
Shifting means shifting all bits and filling the empty spot with a 0
or a 1 (depending on value and/or signedness).
Rotating is shifting all bits and filling the empty spot with the bit
that “fell out” in the end.
AFAIK C does not support rotating, but only shifting (probably because of platform dependencies?). x86 assembler implements both shift and rotate operations.
A explanation better than I can give here, can be found here: http://en.wikibooks.org/wiki/X86_Assembly/Shift_and_Rotate