I have a function which checks, whether a bit in an int is set or not.
But I think there will be a much faster implementation, since this one is linear and can’t be the most efficient one, although I know the int should be between 1 and 1024.
public static int getBitPos(final int n) {
if (Integer.bitCount(n) != 1)
return Constants.UNDEFINED;
else {
for (int i = 0; i < Integer.MAX_VALUE; ++i) {
if (testBit(n, i))
return i;
}
}
return Constants.UNDEFINED;
}
Where testBit is the following standard function:
public static boolean testBit(final int n, final int pos) {
int mask = 1 << pos;
return (n & mask) == mask;
}
But there mast be a faster way, isn’t there? If I have the value 17 and I want to know if the 4th bit (n = 8) is set? There should be a faster way to check whether the bit for n=8 is set…
Hope you can help me…
EDIT 1:
Thanks for the support. The comments and answers brought me to my mistake. I was setting the values wrongly, which made it more complicated than needed. I was never good at bit shifting.
I set the value like this, if I wanted the second bit to be set:
value = 2;
If I wanted the 4th bit to be set too, I added the value according to the 4th bit:
value += 8;
So value was 10, and the 2nd and 4th bit were set. So I saved the numbers in my class, instead of the bit-positions (8 as value, instead of 4 for the 4th bit, …).
After changing this, I could get rid of my unnecessary function, which was way over the top!
Thanks for all help!
Your code always returns the lowest bit that is 1, if there is only one. You can achieve the same by doing this:
Your code would be