bit shifts and c++

Dec 28, 2007 16:51

So, I remembered hearing in school that the C++ spec didn't define whether or not a bitwise right-shift was done with an arithmetic or a logical shift (sar and shr for the x86 people). Well, turns out this is partially right. Here's the relevant clause:
Clause 5.8.3:
The value of E1 >> E2 is E1 right shifted E2 bit positions. If E1 has an ( Read more... )

Leave a comment

Comments 3

evgnyg December 29 2007, 05:02:30 UTC
heh, i got fucked by the >> vs >>> in java a few weeks ago when i was writing an iterator over bitfields and meant the triple but just did the double...

Reply


zanfur December 29 2007, 14:12:44 UTC
Funny, that...isn't that the only situation where the results of an arithmetic and logical shift would differ?

Reply

zanfur December 29 2007, 14:26:56 UTC
Also, I would read that spec to say "It's a logical bitwise shift to the right. For positive integers, and be equal to the left operand divided by the quantity 2 raised to the power of the right operand, round down. The negative numbers are represented differently on different architectures, so the resulting value depends on the implementation."

I know from experience that >> doesn't mean "either logical or arithmetic depending on context". It's always the same command, if you check the assembly. I think the representation of negative numbers (two's complement, one's complement, sign bit, etc.) is implementation-dependent, making the logical shift operator result for negative numbers unspecifiable by the standard. (Except to say that it's gonna be the value, bit-shifted to the right, whatever that turns out to be.)

Reply


Leave a comment

Up