Code

#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", &reg, &pos);
    printf("%u", is_bit_set(reg, pos));
    return 0;
}

Solving Approach

✅ Is Bit Set — Compact Solution Approach

1️⃣ Create mask for the target bit

1 << pos

This creates a number where only the pos bit is 1.

2️⃣ Use AND to isolate the bit

reg & (1 << pos)

Why AND?

  • If that bit is 1 → result is non-zero
  • If that bit is 0 → result is 0

3️⃣ Convert result to 0 or 1

Best compact way:

(reg >> pos) & 1

💡 Final Clean One-Line Logic

return (reg >> pos) & 1;

Why this works

  • reg >> pos → brings target bit to LSB
  • & 1 → extracts only that bit
  • Directly returns 0 or 1

✔ No condition needed
✔ Constant time
✔ Embedded-friendly
✔ Interview-preferred

 

 

Upvote
Downvote
Loading...

Input

4 2

Expected Output

1