Set or Clear a Specific Bit in a Register

Code

#include <stdio.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    // Check the mode
    if (mode == 1) { // Mode is 1, aka evaluates to a true value
        // Mode is 1, we will be setting the value so we use the bitwise OR operation
        // A 1 left shifted into the correct pos
        reg |= (1 << pos);
    } else if (mode == 0) { // Mode is 0, aka evaluates to a false value
        // Mode is 0, we will be clearing the value so we use the bitwise AND operation
        // A 0 left shifted into the correct pos
        reg &= ~(1 << pos);
    }

    // Return the modified register value
    return reg;
}


int main() {
    unsigned char reg;
    int pos, mode;
    scanf("%hhu %d %d", &reg, &pos, &mode);
    printf("%d", modifyBit(reg, pos, mode));
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10