Quiz Entry - updated: 2026.07.10
How do you check if a specific bit is set in C?
AND the value with a mask that has only that bit set, then test for non-zero: if (flags & (1 << n)) is true exactly when bit n is set.
if (flags & (1 << bit_position)) {
// Bit is set
}
// Or with named constants:
// bit 0
#define FLAG_READ 0x01
// bit 1
#define FLAG_WRITE 0x02
// bit 2
#define FLAG_EXEC 0x04
if (flags & FLAG_EXEC) {
// Execute permission is set
}
How it works:
// 00000101
flags = 0x05;
// 00000100 (FLAG_EXEC)
mask = 0x04;
// Non-zero = true!
flags & mask = 0x04
// 00000011
flags = 0x03;
// 00000100
mask = 0x04;
// Zero = false
flags & mask = 0x00
Get the actual bit value (0 or 1):
int bit = (flags >> bit_position) & 1;
// or
int bit = (flags & (1 << bit_position)) ? 1 : 0;