#include <stdio.h> #include <stdint.h> uint8_t is_bit_set(uint8_t reg, uint8_t pos) { if (reg & (1<<pos)){ return 1; } else return 0; } int main() { uint8_t reg, pos; scanf("%hhu %hhu", ®, &pos); printf("%u", is_bit_set(reg, pos)); return 0; }
1️⃣ Create mask for the target bit
1 << pos
This creates a number where only the pos bit is 1.
pos
1
2️⃣ Use AND to isolate the bit
reg & (1 << pos)
Why AND?
0
3️⃣ Convert result to 0 or 1
Best compact way:
(reg >> pos) & 1
return (reg >> pos) & 1;
reg >> pos
& 1
✔ No condition needed✔ Constant time✔ Embedded-friendly✔ Interview-preferred
Test Cases
Test Results
Input
4 2
Expected Output