Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's the reason high-level languages like C#/Java mask the bit shift count operand?
    primarykey
    data
    text
    <p>This is more of a language design rather than a programming question.</p> <p>The following is an excerpt from <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.19" rel="nofollow noreferrer">JLS 15.19 Shift Operators</a>:</p> <blockquote> <p>If the promoted type of the left-hand operand is <code>int</code>, only the five lowest-order bits of the right-hand operand are used as the shift distance.</p> <p>If the promoted type of the left-hand operand is <code>long</code>, then only the six lowest-order bits of the right-hand operand are used as the shift distance.</p> </blockquote> <p>This behavior is also <a href="http://msdn.microsoft.com/en-us/library/aa691377%28VS.71%29.aspx" rel="nofollow noreferrer">specified in C#</a>, and while I'm not sure if it's in the official spec for Javascript (if there's one), it's also true based on my own test at least.</p> <p>The consequence is that the following is true:</p> <pre><code>(1 &lt;&lt; 32) == 1 </code></pre> <p>I understand that this specification is probably "inspired" by the fact that the underlying hardware only takes 5 bits for the count operand when shifting 32-bit values (and 6 bits for 64-bit), and I can understand such behavior specified at the JVM level for example, but why would high level languages such as C# and Java retain this rather low-level behavior? Shouldn't they provide a more abstract view beyond the hardware implementation and behave more intuitively? (Even better if they can take a negative count to mean to shift in the OTHER direction!)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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