Reputation: 13034
I have a specific C bit-shifting scenario that I do not believe is covered on Stack Overflow yet. (If it is, I haven't been able to find it!)
This exercise is using signed int
s as the data type.
Take the value 0x80000000
(which is just a 1 in the most significant bit.)
Shift it right once on a machine using arithmetic right-shifts (which mine does).
Result = 0xC0000000
(1100 0000 in leftmost byte).
Continue shifting it and you should be filling up with ones, from the left to the right.
Result = 0xFFFFFFFF
(All ones.)
However: Try the same example but shift one extra position, all together:
0x80000000 >> 0x00000020
(Right shift 32 times)
Your result? I don't know. My result was not all ones. In fact, I got 0x00000001
which was NOT my desired behavior. Why is this? Is it machine specific?
(Context: Homework assignment limiting my operations to a few bit operators to solve a puzzle. This is an aspect to a puzzle but is far from the entire question.)
Upvotes: 3
Views: 11250
Reputation: 7742
You are not allowed to shift a value more than it's width. How much is the with of an int number ? Well, in a 32-bit system it's 32 bit. If you try to shift an int with more than 32 in gcc, you get this warning :
warning: right shift count >= width of type [enabled by default]
If you want to get 0xFFFFFFFF
you have to shift if 31 times, not 32 times. Think about it !
Upvotes: 1
Reputation: 3271
It's undefined behavior
Why doesn't left bit-shift, "<<", for 32-bit integers work as expected when used more than 32 times?
which means you should avoid it like the plague. Here's some links including "What every C programmer should know about undefined behavior": http://lwn.net/Articles/511767/
Upvotes: 6
Reputation: 74330
Here is a quote about this from the C99 standard:
6.5.7 Bitwise Shift Operators [...]
3 [...] If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
With credit to the original source.
Upvotes: 2
Reputation: 399703
Shifting by the number of bits of the operands has undefined behavior, which is why you're getting "unexpected" results.
Upvotes: 5