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)?
You have to check bit by bit, with a function more or less like this:
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:
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:
Math.log(y) / Math.log(2)
finds thex
in2^x = y
and thex % 1
tells us ifx
is a whole number.x
will only be a whole number if a single bit is set, and thus, only one animal is selected.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):
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):