Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It looks like your implementation is probably doing an arithmetic bit shift with two's complement numbers. In this system, it shifts all of the bits to the right and then fills in the upper bits with a copy of whatever the last bit was. So for your example, treating int as 32-bits here:</p> <pre><code>nPosVal = 00000000000000001111111111111111 nNegVal = 11111111111111110000000000000001 </code></pre> <p>After the shift, you've got: </p> <pre><code>nPosVal = 00000000000000000111111111111111 nNegVal = 11111111111111111000000000000000 </code></pre> <p>If you convert this back to decimal, you get 32767 and -32768 respectively.</p> <p>Effectively, a right shift rounds towards negative infinity.</p> <p><strong>Edit:</strong> According to the Section 6.5.7 of the latest <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1336.pdf" rel="noreferrer">draft standard</a>, this behavior on negative numbers is implementation dependent:<blockquote>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<sup>E2</sup>. If E1 has a signed type and a negative value, the resulting value is implementation-defined.</blockquote></p> <p>Their stated <a href="http://www.open-std.org/JTC1/SC22/WG14/www/C99RationaleV5.10.pdf" rel="noreferrer">rational</a> for this: <blockquote>The C89 Committee affirmed the freedom in implementation granted by K&amp;R in not requiring the signed right shift operation to sign extend, since such a requirement might slow down fast code and since the usefulness of sign extended shifts is marginal. (Shifting a negative two’s complement integer arithmetically right one place is <i>not</i> the same as dividing by two!)</blockquote></p> <p>So it's implementation dependent in theory. In practice, I've never seen an implementation <i>not</i> do an arithmetic shift right when the left operand is signed.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload