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; // 8-bit register value
    int bitPos, mode;

    // Get input from user
    scanf("%hhu %d %d", &reg, &bitPos, &mode);

    // Validate input
    if(bitPos < 0 || bitPos > 7) {
        printf("Error: Bit position must be between 0 and 7.\n");
        return 1;
    }
    if(mode != 0 && mode != 1) {
        printf("Error: Mode must be 0 or 1.\n");
        return 1;
    }

    // Modify the bit only if needed
    if(mode == 1) {
        reg |= (1 << bitPos);   // Set bit
    } else {
        reg &= ~(1 << bitPos);  // Clear bit
    }

    // Print the updated register value
    printf("%d\n", reg);

    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote