1. Set or Clear a Specific Bit in a Register

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    unsigned char mask = 1 << pos;

    // want an if statement here
    if(mode == 0) {
        return reg & ~(mask);
    }

    return reg | mask;
}

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

Simple masking approach that flips the mask if we need to set zero.

 

 

Was this helpful?
Upvote
Downvote