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) {
    // Guard against invalid positions (>= 8) for 8-bit registers
    if (pos >= 8) {
        return reg; // No change if position is out of range
    }
    // Create mask with 1 at 'pos', invert to have 0 at 'pos' and 1 elsewhere, then AND
    uint8_t mask = (uint8_t)~(uint8_t)(1u << pos);
    return reg & mask;
}

int main() {
    uint8_t reg, pos;
    // Read decimal values for simplicity (e.g., reg=7 pos=0), not binary literals
    if (scanf("%hhu %hhu", &reg, &pos) != 2) {
        return 1; // Input error
    }
    uint8_t result = clear_bit(reg, pos);
    printf("%u", result);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

7 0

Expected Output

6