Set or Clear a Specific Bit in a Register

Code

#include <stdio.h>

int main() {
    unsigned char reg;  // 8-bit register (0-255)
    int bitPos, mode;

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

    // Validate bit position
    if (bitPos < 0 || bitPos > 7) {
        printf("Invalid bit position\n");
        return 1;
    }

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

    // Output the modified register value
    printf("%d\n", reg);

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10