Bit shifting a negative number is implementation-behavior in C. The results will depend on your platform, and theoretically could be completely nonsensical. From the C99 standard (6.5.7.5):
> The result of E1 >> E2 is E1
> right-shifted E2 bit positions. If E1
> has an unsigned type or if E1 has a
> signed type and a nonnegative value,
> the value of the result is the
> integral part of the quotient of E1 /
> 2^E2 . If E1 has a signed type and a
> negative value, the resulting value is
> implementation-defined.
The reason this happens is most likely because your compiler uses the x86 SAR (Shift Arithmetic Right) instruction to implement >>. This means sign extension will occur - the most significant bit will be replicated into the new MSB once the value is shifted over. From the [intel manuals][1]:
> The shift arithmetic right (SAR) and
> shift logical right (SHR) instructions
> shift the bits of the destination
> operand to the right (toward less
> significant bit locations). For each
> shift count, the least significant bit
> of the destination operand is shifted
> into the CF flag, and the most
> significant bit is either set or
> cleared depending on the instruction
> type. The SHR instruction clears the
> most significant bit (see Figure 7-8
> in the Intel® 64 and IA-32
> Architectures Software Developer’s
> Manual, Volume 1); the SAR instruction
> sets or clears the most significant
> bit to correspond to the sign (most
> significant bit) of the original value
> in the destination operand. **In effect,
> the SAR instruction fills the empty
> bit position’s shifted value with the
> sign of the unshifted value** (see
> Figure 7-9 in the Intel® 64 and IA-32
> Architectures Software Developer’s
> Manual, Volume 1).
[1]:
[To see links please register here]