All submissions

Set or Clear a Specific Bit in a Register

Code

#include <stdio.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    // Write your code here
    int res = 0 ;
    if (mode == 1)
    {
        res = reg |(1<<pos);
    }
    else
    {
        res = reg &(~(1<<pos));
    }
    return res;
}

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

I had used "if" loop for set and clear condition for set bit used Logical OR operation with shifting 1 bit to pos needed by left shifting <<   ex : 10 = 00001010 | 00001000 = 00001010
for clear bit used AND with a NOT ex 00001010 & ~(00001000) = 00001010 & 11110111 = 00000010 .   

 

 

Loading...

Input

10 3 1

Expected Output

10