1. Set or Clear a Specific Bit in a Register

Back To All Submissions
Previous Submission
Next Submission

Code

/* This code is to set or clear a specific bit 
   submitted by Manish Gowda T
   accomplished by if-else and OR and AND-NOT operators*/




#include <stdio.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    char setter=(1<<pos);
    if(mode==1){
        return reg | setter;
    }
    else{
        return reg &~ setter;
    }
}

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

first we check the mode 
if mode is 1 we perform OR between reg and left shift by pos bits 
else we perform AND-NOT operation between them 

 

 

Was this helpful?
Upvote
Downvote