I have 5 bit numbers like
10000
01000
00100
If only one bit is on in my calculation i have no problem.
but if 2 bits are on then I
Since you only want to isolate it, not get its index, it's easy:
function firstSetBit(number)
{
return number & -number;
}
It works because if you take the two's complement negation of a number, first you complement it, setting all zeroes to the right of the lowest set bit to one and the lowest set bit to zero, then you add one, setting the bits on the right to zero and the lowest set bit becomes one again, ending the carry chain. So the negation of the number has the same "right part", up to and including the lowest set bit, but everything to the left of the lowest set bit is the complement of the input. Thus if you take the bitwise AND of a number with its negation, all the bits to the left of the lowest set bit are cancelled out.
return log2(n & -n) + 1;
this will may help you.
function isolateLowestBit(input)
{
mask = 1;
while (mask <= input)
{
if (mask & input)
{
// found match - mask is set to the value of the lowest bit
return mask;
}
mask *= 2; // shift up mask by one bit
}
// no match
return 0;
}
Beware that bitwise operations in Javascript are a bad idea, since since Javascript numbers aren't naturally integer.
Binary operators usually affect all bits of a number. So, there is no special function to get only the first "1" in number. But you can try such a function:
function filterFirstFoundBit(number)
{
for (var i = 0; i < 32; i++) {
if ((1 << i) & number)
{
return 1 << i;
}
}
return number;
}
document.write(filterFirstFoundBit(9)); //10010
Try it here