title: How do I determine the position of the nth most significand bit set in a 64-bit value?
body: <p>I'm using some long values as bitmaps in a Java program. Here's my method so far:</p>
  
  <pre><code>public class BitmapUtil
  {
      private static final long _B_MASK_LEFT_ON = 0x8000000000000000L;
  
      public static long setNthMsb(int n)
      {
          return BitmapUtil._B_MASK_LEFT_ON &gt;&gt;&gt; n;
      }
  
      public static boolean isNthMsbSet(long b, int n)
      {
          return (b &amp; (BitmapUtil.setNthMsb(n))) != 0L;
      }
  
      public static int getNthMsbPosition(long b, int n)
      {
          int ix = 0;
          while (ix &lt; 64 &amp;&amp; n &gt;= 0) {
              if (BitmapUtil.isNthMsbSet(b, ix)) {
                  if (n == 0) {
                      return ix;
                  } else {
                      n--;
                  }
              }
              ix++;
          }
          return -1;
      }
  }
  </code></pre>
  
  <p>I've seen so many clever bit tricks that I can't help but feeling that there should be a better way. Is there?</p>