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) {
    if (mode==1)
    {
        reg |=(1<<pos);
    }
    else if(mode==0)
    {
        reg &= ~(1<<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

  • If and else for checking the condition , if mode=1 the bit should be set and mode =0 it should be clear.
  • using bit-wise operator like  & and | , to help the register to set the final value of register
  • using left shift bit- wise operator so that at specific position we can clear or set the values

 

 

Was this helpful?
Upvote
Downvote