Bitmask: how to determine if only one bit is set

江枫思渺然 提交于 2019-12-04 23:13:24
Ted Hopp

You can count the number of bits that are set in a non-negative integer value with this code (adapted to JavaScript from this answer):

function countSetBits(i)
{
    i = i - ((i >> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
    return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}

It should be much more efficient than examining each bit individually. However, it doesn't work if the sign bit is set in i.

EDIT (all credit to Pointy's comment):

function isPowerOfTwo(i) {
    return i > 0 && (i & (i-1)) === 0;
}

You have to check bit by bit, with a function more or less like this:

function p2(n) {
  if (n === 0) return false;
  while (n) {
    if (n & 1 && n !== 1) return false;
    n >>= 1;
  }

  return true;
}

Some CPU instruction sets have included a "count set bits" operation (the ancient CDC Cyber series was one). It's useful for some data structures implemented as bit collections. If you've got a set implemented as a string of integers, with bit positions corresponding to elements of the set data type, then getting the cardinality involves counting bits.

edit wow looking into Ted Hopp's answer I stumbled across this:

function p2(n) {
  return n !== 0 && (n & (n - 1)) === 0;
}

That's from this awesome collection of "tricks". Things like this problem are good reasons to study number theory :-)

If you're looking to see if only a single bit is set, you could take advantage of logarithms, as follows:

var singleAnimal = (Math.log(onTheFarm) / Math.log(2)) % 1 == 0;

Math.log(y) / Math.log(2) finds the x in 2^x = y and the x % 1 tells us if x is a whole number. x will only be a whole number if a single bit is set, and thus, only one animal is selected.

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