I've been breezing through my C book and having fun while doing it. Today, I reached the Binary, Hex, and Dec section of my book. I understood it all well except a section about bit flags. The book says
It then states:A common use for the bitwise operators is to combine several values in a single variable for efficiency. For instance, a program with several "flag" variables, which always have a value of either 1 or 0 (representing true or false states), would normally require eight bits of memory each. The storage of a single digit only requires a single bit, however, so up to eight flags can be combined in a single variable, as seen with the "state" variable in this example:
Code:#include <stdio.h> #define FLAG_1 1 /* 0000 0001 */ #define FLAG_2 2 /* 0000 0010 */ #define FLAG_3 4 /* 0000 0100 */ #define FLAG_4 8 /* 0000 1000 */ #define FLAG_5 16 /* 0001 0000 */ #define FLAG_6 32 /* 0010 0000 */ #define FLAG_7 64 /* 0100 0000 */ #define FLAG_8 128 /* 1000 0000 */ int main() { int state = 44; /* 0010 1100 */ if ((state & FLAG_1) > 0) printf("Flag 1 is set\n"); if ((state & FLAG_2) > 0) printf("Flag 2 is set\n"); if ((state & FLAG_3) > 0) printf("Flag 3 is set\n"); if ((state & FLAG_4) > 0) printf("Flag 4 is set\n"); if ((state & FLAG_5) > 0) printf("Flag 5 is set\n"); if ((state & FLAG_6) > 0) printf("Flag 6 is set\n"); if ((state & FLAG_7) > 0) printf("Flag 7 is set\n"); if ((state & FLAG_8) > 0) printf("Flag 8 is set\n"); return 0; }
The part I don't understand is that the code above prints this:The flag constants have values of increasing powers of 2 to represent individual binary numbers which do not overlap. The state variable value contains an integer total of those flags which are set. For instance, if the state value is 1, flag 1 is set, if the state value is 3, both flags 1 and 2 are set, etc...
But 3 + 4 + 6 is not 44. I thought the book said that "the state variable contains an integer total of those flags which are set." Can someone please clarify. Also, what exactly what you want to use this for? Thanks. Much appreciated.Flag 3 is set
Flag 4 is set
Flag 6 is set
All quoted material is copyright Computer Step 2004 from the book C Programming in Easy Steps by Mike McGrath