1. Set or Clear a Specific Bit in a Register

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

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

    // Input: register value, bit position, mode
    scanf("%hhu %d %d", &reg, &pos, &mode);

    if (pos < 0 || pos > 7) {
        printf("Invalid bit position\n");
        return 0;
    }

    if (mode == 1) {
        // Set the bit
        reg = reg | (1 << pos);
    } else if (mode == 0) {
        // Clear the bit
        reg = reg & ~(1 << pos);
    } else {
        printf("Invalid mode\n");
        return 0;
    }

    // Output result
    printf("%d\n", reg);

    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote