Is the Bit Set

RohitTelkar
RohitTelkar

Code

#include <stdio.h>
#include <stdint.h>

uint8_t is_bit_set(uint8_t reg, uint8_t pos) {
    
    return (reg >> pos) & 1;
}

int main() {
    uint8_t reg, pos;
    scanf("%hhu %hhu", &reg, &pos);
    printf("%u\n", is_bit_set(reg, pos));
    return 0;
}

Solving Approach

First, we shift the register's bits to the right by the given position.

 

Let’s walk through an example:
Suppose the input is:

Register (reg) = 4
Position (pos) = 2

 

The binary representation of 4 is:

0000 0100

Now, we shift the bits to the right by 2 positions:
After shifting 1 bit to the right:

0000 0010

After shifting another bit to the right:

0000 0001

At this point, the bit we are interested in is now at the least significant position (the rightmost bit).
Next, to check if this bit is set (i.e., if it is 1), we perform a bitwise AND with 1:

0000 0001 & 0000 0001 = 0000 0001

 

The result is 1, which means the bit at position 2 is set.
If the result had been 0, it would mean the bit is not set.

Loading...

Input

4 2

Expected Output

1