I'm using some long values as bitmaps in a Java program. Here's my method so far:
public class BitmapUtil
{
private static final long _B_MASK_LEFT_ON = 0x8000000000000000L;
public static long setNthMsb(int n)
{
return BitmapUtil._B_MASK_LEFT_ON >>> n;
}
public static boolean isNthMsbSet(long b, int n)
{
return (b & (BitmapUtil.setNthMsb(n))) != 0L;
}
public static int getNthMsbPosition(long b, int n)
{
int ix = 0;
while (ix < 64 && n >= 0) {
if (BitmapUtil.isNthMsbSet(b, ix)) {
if (n == 0) {
return ix;
} else {
n--;
}
}
ix++;
}
return -1;
}
}
I've seen so many clever bit tricks that I can't help but feeling that there should be a better way. Is there?