/** * A very trivial example of a bit mask in use * Bit masks can make otherwise complex comparisons * over multiple values can be quite easy to implement * * The core idea is that when you & the value together with the * mask, you old get a non-zero number iff the value has a * one in the same position as in the mask. * * @author gtowell * Created: April 2021 * **/ #include #define OPTA 1 #define OPTB 2 #define OPTC 4 #define OPTD 8 /** * Get input from user. * All use input is stored in bits within the single char * that is retured. Hence, the char should never be read * as a char * @return a char containing bits set according to use input * **/ char getUserSel() { char selectedOpts = 0; char c[100]; while (1) { printf("Enter a letter: "); fgets(c, 99, stdin); switch (c[0]) { case 'a': case 'A': selectedOpts = selectedOpts | OPTA; break; case 'b': case 'B': selectedOpts |= OPTB; break; case 'c': case 'C': selectedOpts |= OPTC; break; case 'd': case 'D': selectedOpts |= OPTD; break; default: return selectedOpts; } } } int main(int argc, char const *argv[]) { char userSel = getUserSel(); //printf("%d %d %d\n", userSel, (OPTA | OPTB), (userSel & (OPTA | OPTB))); // Two different bitmasks if (userSel & (OPTA | OPTB)) printf("user selected A or B\n"); if (userSel & (OPTA | OPTC | OPTD)) printf("user selected A or C or D\n"); return 0; }