Read Bits with AND
Read one indicator bit
The workshop panel has four indicator switches. Each can be on (1) or off (0), so their states fit in the low bits of an unsigned int. Number bit positions from the right, starting at 0. Their values are 1, 2, 4, and 8. Thus 1010 means 8 + 2, or decimal 10.
Hexadecimal uses base 16: digits 0–9 then A–F for 10–15. The prefix 0x marks a hex constant, so 0xA also means 10. Standard C11 does not define the 0b binary-literal prefix, so the code uses hex.
A mask with one set bit selects one position. Bitwise & keeps a 1 only where both values have a 1.
#include <stdio.h>
int main(void) {
unsigned int lights = 0xAu;
unsigned int repair = 0x2u;
printf("Repair light on: %u\n", (unsigned int) ((lights & repair) != 0u));
printf("First light on: %u\n", (unsigned int) ((lights & 0x1u) != 0u));
return 0;
}
The repair mask checks the second bit from the right; it is on, while the lowest bit is off. Run and check that the repair light reports 1 and the first light reports 0. If lights were 0xBu (1011), only the first-light result would change. The u suffix makes these constants unsigned.
lights & repair gives 2, not 1. Comparing that result with zero turns it into an int truth value, 0 or 1. The cast (unsigned int) matches %u. Here “truth value” describes the result; it does not require a bool variable or <stdbool.h>. Keep parentheses around the AND before !=: equality comparisons bind more tightly than bitwise AND. & works bit by bit; && tests whether two whole expressions are nonzero.