Find the lowest set bit

前端 未结 4 1754
名媛妹妹
名媛妹妹 2021-01-06 21: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

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-06 21:25

    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

提交回复
热议问题