title: Fast way of finding most and least significant bit set in a 64-bit integer
body: <p>There are a lot of questions about this on StackOverflow. <strong>A lot</strong>. However I cannot find an answer that:</p>
  
  <ul>
  <li>Works in C#</li>
  <li>Works for 64-bit integers (as opposed to 32-bit)</li>
  </ul>
  
  <p>Faster than:</p>
  
  <pre><code>private static int Obvious(ulong v)
  {
      int r = 0;
      while ((v &gt;&gt;= 1) != 0) 
      {
          r++;
      }
      return r;
  }
  </code></pre>
  
  <p>Or even</p>
  
  <pre><code>int r = (int)(Math.Log(v,2));
  </code></pre>
  
  <p>I'm assuming a 64-bit Intel CPU here.</p>
  
  <p>One useful reference is the <a href="http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn" rel="nofollow noreferrer">Bit Hacks page</a> and another is <a href="http://www.jjj.de/fxt/fxtbook.pdf" rel="nofollow noreferrer">fxtbook.pdf</a>
  However, while these gives useful direction to approach the problem, they do not give a ready answer.</p>
  
  <p>I'm after a re-usable function that can do something similar to <a href="https://docs.microsoft.com/en-us/cpp/intrinsics/bitscanforward-bitscanforward64" rel="nofollow noreferrer">_BitScanForward64</a> and <a href="https://docs.microsoft.com/en-us/cpp/intrinsics/bitscanreverse-bitscanreverse64" rel="nofollow noreferrer">_BitScanReverse64</a> only for C#.</p>