Is the Bit Set

durgaramprasadtula
durgaramprasadtula

Code

#include <stdio.h>

// Function to check if the bit is set
int isBitSet(unsigned char reg, int pos) {
    return (reg & (1 << pos)) ? 1 : 0;
}

int main() {
    unsigned char reg;
    int pos;

    // Input: 8-bit register and position
    scanf("%hhu %d", &reg, &pos);

    // Output: 1 if set, 0 otherwise
    printf("%d", isBitSet(reg, pos));

    return 0;
}

Solving Approach

Use Bitwise AND:

  • reg & (1 << pos) isolates the bit at position pos.
  • If the result is non-zero → bit is set → return 1.
  • If the result is zero → bit is not set → return 0.

 

 

Loading...

Input

4 2

Expected Output

1