Clear the Bit in an 8-bit Register

Code

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

uint8_t clear_bit(uint8_t reg, uint8_t pos) {
    // Your code here
    reg &= ~(1<<pos);
    return reg;
}

int main() {
    uint8_t reg, pos;
    scanf("%hhu %hhu", &reg, &pos);
    uint8_t result = clear_bit(reg, pos);
    printf("%u", result);
    return 0;
}

Solving Approach

  1. To clear a bit, its as simple as AND-ing with a 0, But wait, we dont want to clear the whole register.

  2. To have the other values remain the same, think of AND-ing a 0 (Reg) with a 1 (Mask), the value would be 0, Which means that its unchanged.

  3. Now thing of AND-ing a 1 (Reg) with a 1 (Mask), the value would still be 0. Which means that it also remains unchanged.

  4. This simply means that we need to AND, the bit position we want to clear with a zero and all other bits with a 1. How do we achieve this?

  5. We left shift the value 1 to the position we want to clear, then invert the value such that all other bits become 1 and the bit position we are targeting has a zero on the mask. We finally AND the register and clear only one bit!

 

 

Upvote
Downvote
Loading...

Input

7 0

Expected Output

6