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) {
    // Write your code here
    unsigned char temp = 1<<pos;
    if(mode)
        return reg|temp;
    else
        return reg^temp;
}

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

Eg: reg = 1010

To set 3rd bit: temp = 1<<3 = 0100, return (1010 | 0100) = 1110

To clear 2nd bit: temp = 1<<2 = 0010, return (1010 ^ 0010) = 1000

 

 

Was this helpful?
Upvote
Downvote