Bitmask: how to determine if only one bit is set

bit-masks, bitmask, javascript

Solution

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;
}

Problem

If I have a basic bitmask... ``` cat = 0x1; dog = 0x2; chicken = 0x4; cow = 0x8; // OMD has a chicken and a cow onTheFarm = 0x12; ``` ...how can I check if only one animal (i.e. one bit) is set? The value of `onTheFarm` must be 2n, but how can I check that programmatically (preferably in Javascript)?

Original source

Related problems