3

For GCC 32 bits, -1 >> 1 returns me FFFFFFFF, but I thought after 2's complement, I will get 0111 1111 ... 1111 which should be 7fff ffff. did i miss something?

web rocker
  • 217
  • 1
  • 3
  • 10
  • 1
    "but I thought after 2's complement" - shifting has nothing to do with 2's complement – Mitch Wheat Apr 21 '14 at 08:13
  • Duplicate of https://stackoverflow.com/questions/23180157/what-is-the-value-of-0-in-c/23180242#23180242. – user3553031 Apr 21 '14 at 08:14
  • possible duplicate of [Right bit-shift giving wrong result, can someone explain](http://stackoverflow.com/questions/23176797/right-bit-shift-giving-wrong-result-can-someone-explain) – Shafik Yaghmour Apr 21 '14 at 09:29
  • you are missing three points: One is answer below, (2) How 2'complement works (3) there is concept of signed and unsigned shifts --- negative numbers in most C implementation preserves sign but hence are === to arithmetic shifts, to perform unsigned shift use `unsigned(-1) >> 1`. Read my answer [what is the value of ~0 in C?](http://stackoverflow.com/a/23180179/1673391) to get some idea, let me know if you have confusion I will post an answer. – Grijesh Chauhan Apr 21 '14 at 10:32
  • Sorry I mean `((unsigned)-1) >> 1);` see code @ [codepad](http://codepad.org/PPrnpJzi) outputs `2147483647` that is `7F FF FF FF` – Grijesh Chauhan Apr 21 '14 at 10:38

2 Answers2

10

Under most implementations, that operator does an arithmetic shift for signed types, so it preserves the sign bit (which is the leftmost bit), in this case 1.

As @Clifford correctly pointed out, the language standard leaves the implementation of >> up to the implementor.

See the Wikipedia article for details.

Clifford
  • 88,407
  • 13
  • 85
  • 165
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • No - it is implementation defined behavior for negative values. An implementation may replace the vacated bit with 0 or 1. What you have described here is "typical" behavior (and may even be universal), but it is not guaranteed by the language definition. – Clifford Apr 21 '14 at 08:33
  • @Clifford, That is true. I will amend it to be more careful about the wording. – merlin2011 Apr 21 '14 at 08:36
  • @Clifford, Updated. Please let me know if anything else is incorrect. – merlin2011 Apr 21 '14 at 08:38
2

For E1 >> E2, if E1 is negative, then the behavior is implementation-defined, which means different compilers could use different strategies to implement it.

Apparently GCC choose arithmetic shift, as pointed out by @merlin2011

Lee Duhem
  • 14,695
  • 3
  • 29
  • 47