Counting with a bit mask

I am looking for a way to list the values โ€‹โ€‹that match a specific bit mask.

For example, I want to list all the bytes that contain a pattern 0xb5


A simple program to achieve this goal:

#include <stdio.h>
#include <stdint.h>

/* prints out b5, b7, bd, bf, f5, f7, fd, ff */
int main(int argc, const char ** argv) {    
    const uint8_t mask = 0xb5;
    uint8_t i = 0;

    while(true) {
        if((i & mask) == mask) printf("%x\n", i);
        if(i == UINT8_MAX) break;
        i++; /* Replace by something smarter. */
    return 0;


However, regardless of the mask, this cycle will repeat UINT8_MAX

once. Is there a neat trick I can use to automatically increment i

to the next value that matches the mask?


source to share

3 answers

You can only count through "wildcard bits", for example:

x = (x + 1) | pattern;


Assuming you start with pattern

(wildcard bit is zero).

The idea here is that the "pattern bits" are 1, so when you add one, the hyphen (if there is one) moves through them to the next section of "wildcard bits". Of course, when the carry has passed, it leaves the "pattern bits" at 0, so they are placed again.



Instead, i++

you can usei = ((i << 1) | 1);



A little variation on a theme well known by @harold

while (1) {
  printf("%x\n", i);  // no need for mask test
  if (i == UINT8_MAX)
  do {
   } while ((i & mask) != mask);




All Articles