title: Unsigned right shift operator '>>>' in Swift
body: <p>How would you implement the equivalent to Java's unsigned right shift operator in Swift? </p>
  
  <p>According to <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html" rel="nofollow noreferrer">Java's documentation</a>, the unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.</p>
  
  <p>So, for instance,</p>
  
  <pre><code>    long s1 = (-7L &gt;&gt;&gt; 16); // result is 281474976710655L
      long s2 = (-7L &gt;&gt; 16); // result is -1
  </code></pre>
  
  <p>In order to implement this in Swift, I would take all the bits except the sign bit by doing something like,</p>
  
  <pre><code>    let lsb = Int64.max + negativeNumber + 1
  </code></pre>
  
  <p>Notice that the number has to be negative! If you overflow the shift operator, the app crashes with EXC_BAD_INSTRUCTION, which it's not very nice...
  Also, I'm using Int64 on purpose. Because there's no bigger datatype, doing something like (1 &lt;&lt; 63) would overflow the Int64 and also crash. So instead of doing ((1 &lt;&lt; 63) - 1 + negativeNumber) in a bigger datatype, I wrote it as Int64.max + negativeNumber - 1.</p>
  
  <p>Then, shift that positive number with the normal logical shift, and OR the bit from the sign in the first left bit after the sign.</p>
  
  <pre><code>    let shifted = (lsb &gt;&gt; bits) | 0x4000000000000000
  </code></pre>
  
  <p>However, that doesn't give me the expected result,</p>
  
  <pre><code>    ((Int64.max - 7 + 1) &gt;&gt; 16) | 0x4000000000000000 // = 4611826755915743231
  </code></pre>
  
  <p>Not sure what I'm doing wrong... 
  Also, would it be possible to name this operator '>>>' and extend Int64?</p>
  
  <p>Edit:
  Adding here the solution from OOper below,</p>
  
  <pre><code>infix operator &gt;&gt;&gt; : BitwiseShiftPrecedence
  
  func &gt;&gt;&gt; (lhs: Int64, rhs: Int64) -&gt; Int64 {
    return Int64(bitPattern: UInt64(bitPattern: lhs) &gt;&gt; UInt64(rhs))
  }
  </code></pre>
  
  <p>I was implementing the Java Random class in Swift, which also involves truncating 64-bit ints into 32-bit. Thanks to OOper I just realized I can use the truncatingBitPattern initializer to avoid overflow exceptions. The function 'next' as described <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Random.html" rel="nofollow noreferrer">here</a> becomes this in Swift,</p>
  
  <pre><code>var seed: Int64 = 0
  private func next(_ bits: Int32) -&gt; Int32 {
      seed = (seed &amp;* 0x5DEECE66D &amp;+ 0xB) &amp; ((1 &lt;&lt; 48) - 1)
      let shifted : Int64 = seed &gt;&gt;&gt; (48 - Int64(bits))
      return Int32(truncatingBitPattern: shifted)
  }
  </code></pre>