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 |= (1U << pos); // SET BIT
    } else {
        reg &= ~(1U << 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

The mode can either be 1 or 0, so an if-else statement must be used for each case. We need there to be code to either set/clear the bit we want to change.

  1. If the mode is set to 1, use the bitwise OR operator on reg to shift the bit once to the left.
  2. If the mode is set to 0, use the bitwise AND operator, and invert the bits using ~.

Return the result register value each time.

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10