Find the lowest set bit

梦想的初衷 提交于 2020-01-15 10:18:07

问题


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 want to select only the first on bit for example

10010

i want to treat it as 2 instead of the number 18

is there any bitwise operation which may i use in such sitution?


回答1:


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.




回答2:


return log2(n & -n) + 1;

this will may help you.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/12247186/find-the-lowest-set-bit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!