C Programming: Memory, Pointers and the Stack ยท Structs and Types
Store several on/off flags in one int: turn bits on with |, test with &, turn off with & ~, and shift.
#include <stdio.h>
#define FLAG_READ 1 /* 001 */
#define FLAG_WRITE 2 /* 010 */
#define FLAG_EXEC 4 /* 100 */
int main(void) {
int perms = 0;
perms = perms | FLAG_READ; /* turn a bit on */
perms = perms | FLAG_EXEC;
int can_write = (perms & FLAG_WRITE) != 0;
perms = perms & ~FLAG_EXEC; /* turn a bit off */
int shifted = 1 << 4; /* 16 */
int toggled = 6 ^ 3; /* 110 ^ 011 = 101 */
printf("%d %d %d %d\n", perms, can_write, shifted, toggled);
return 0;
}perms is created on the stack with the value 0.toggled is created on the stack with the value 5.1 0 16 5.0.