Incrementing with a bitmask

A small trick to increase readability when using bitwise flags.

Bitmasks are fun. There’s lots of little tricks you can do with them. A common situation is checking for the presence of a flag among elements in a linked list, or some similar data structure. I came across a trick a few years ago that makes it drop-dead simple.

Let’s say we needed to check for AUsefulFlag in the flags element of each node, and total how many elements in the linked list had the flag.

uint64_t count = 0;
for(Node *iter = head; iter != NULL; iter = iter->next)
{
    count += !!(iter->flags & AUsefulFlag);
}

After execution, count is the number of items which have AUsefulFlag set.

Double-not (!!) is one of those useful operations which are especially useful with bitmasks. It may require a double-take at first, but it behaves exactly how you’d think.

!! of 1 is 1. !! of 0 is 0. In fact, !! of any true value evaluates to 1, so we can use it to transform something like 0b00001000 to simply 1 and increment by that value.