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

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 the  mode is 0 - to clear the bit.. so we need to get zero at the particular position so create a mask such that only that position is zero... remaining bits are 1.. then performing and operation gives the result..

if the mode is 1 - to set the bit.. so we need to get 1 at that particular position so moving mask  to that position and performming or operation so get the result

 

 

Loading...

Input

10 3 1

Expected Output

10