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 |= (1 << pos);  // Set bit
   } else {
        reg &= ~(1 << pos); // Clear bit
   }
     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

To set a bit a bitwwise OR (|= (1 << 2): sets bit number 3 (in binary starting with bit number 0, 1, 2 and so on) to 1) and for cleaning a bit a bitwse  AND (&= ~(1 << 3) clears bit number 4) needed

 

 

 

Loading...

Input

10 3 1

Expected Output

10