title: Bitwise Rotate Right
body: <p>I am trying to convert this C function into Python;</p>
  
  <pre><code>typedef unsigned long var;
      /* Bit rotate rightwards */
      var ror(var v,unsigned int bits) {
          return (v&gt;&gt;bits)|(v&lt;&lt;(8*sizeof(var)-bits));
      }
  </code></pre>
  
  <p>I have tried Googling for some solutions, but I can't seem to get any of them to give the same results as the one here. </p>
  
  <p>This is one solution I have found from another program;</p>
  
  <pre><code>def mask1(n):
     """Return a bitmask of length n (suitable for masking against an
        int to coerce the size to a given length)
     """
     if n &gt;= 0:
         return 2**n - 1
     else:
         return 0
  
  def ror(n, rotations=1, width=8):
      """Return a given number of bitwise right rotations of an integer n,
         for a given bit field width.
      """
      rotations %= width
      if rotations &lt; 1:
          return n
      n &amp;= mask1(width)
      return (n &gt;&gt; rotations) | ((n &lt;&lt; (8 * width - rotations)))
  </code></pre>
  
  <p>I am trying to btishift <code>key = 0xf0f0f0f0f123456</code>. The C code gives <code>000000000f0f0f12</code> when it is called with; <code>ror(key, 8 &lt;&lt; 1)</code> and Python gives; <code>0x0f0f0f0f0f123456</code> (the original input!)</p>