All submissions

Set or Clear a Specific Bit in a Register

Code

#include <stdio.h>
#include <math.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    // Write your code here
    int modifier;
    modifier= pow(2,pos);
    switch (mode) {
    case 0:
        return reg & (0XFF^modifier);

    case 1:
    default:
        return reg | modifier;
    }
}

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

Compute the modifier as 2 to th epower of the bit position.

modifier=pow(2,pos)

To clear the bit, get the do bitwise AND with the ones compliment of the modifier.

To set the bit, do a bitwise OR with the computed modifier

 

 

Loading...

Input

10 3 1

Expected Output

10