Find the least significant bit of a set

I have 5 bit numbers like

10000
01000
00100

If only one bit is included in my calculation, I have no problem.

but if 2 bits are on, then I want to select only the first bit, for example

10010

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

is there a bitwise operation that i can use in such a setting?

+1
source share
4 answers

Since you only want to isolate it, don't get its index, it's easy:

function firstSetBit(number)
{
    return number & -number;
}

, , , , , , , . , " ", , , , . , , .

+7

log2 (n & -n) + 1;

.

0

. , "1". ​​:

function filterFirstFoundBit(number)
{
    for (var i = 0; i < 32; i++) {
        if ((1 << i) & number)
        {
            return 1 << i;
        }
    }
    return number;
}
document.write(filterFirstFoundBit(9)); //10010​​​​​​​​

-1
source
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 is a bad idea, because since Javascript numbers are not natural integers.

-1
source

Source: https://habr.com/ru/post/1686773/


All Articles