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
    reg = (reg & ~(1 << pos) | mode << pos);
    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

  1. Perform a clear bit by applying AND with an inverse mask
  2. do the bitwise OR on the bit in the position to set the value to the mode 1 (set bit) or 0 (clear bit).

 

 

Was this helpful?
Upvote
Downvote