Set or Clear a Specific Bit in a Register

Code

#include <stdio.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    static const int MODE_CLEAR = 0;
    static const int MODE_SET = 1;
    static const char BIT_0_MASK = 1u;

    char bit_pos_mask = BIT_0_MASK << pos;

    if (mode == MODE_CLEAR) {
        return (reg & (~bit_pos_mask));

    } else if (mode == MODE_SET) {
        return (reg | bit_pos_mask);

    } else {
        // Error
        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