Search code examples
bit-manipulationbit-fieldsbitmask

Bitfield mask/operations with optional items


I'm trying to find a way to handle several bitfield cases that include optional, required, and not allowed positions.

yy?nnn?y
11000001

?yyy?nnn
01110000

nn?yyy?n
00011100

?nnn?yyy
00000111

In these four cases, the ? indicates that the bit can be either 1 or 0 while y indicates a 1 is required and n indicates that a 0 is required. The bits to the left/right of the required bits can be anything and the remaining bits must be 0. Is there a masking method I can use to test if an input bit set satisfies one of these cases?


Solution

  • Absolutely, but of course it depends on how you represent the "templates".

    For example, say you represent them as a pair (z, o) where z has a 1 for every bit that is allowed to be 0 and o has a 1 for every bit that is allowed to be 1 (as in the paper I linked to in the comments). Then to test x against it you could do:

    if ((x | z) == -1 && (x & o) == x)
        passes test
    

    You could also represent the templates as a pair (mask, bits), where mask is a mask of all bits that have to match (ie 0 means ?, 1 means a fixed bit) and bits is the values of the fixed bits. Then you could test x like:

    if ((x & mask) == bits)
        passes test
    

    That's in general. If your problem has a special form, as it does in your question, you could use specialized tests.