1. Set or Clear a Specific Bit in a Register

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    return mode?
            reg | (1 << pos)
          : reg & ~(1 << pos);
}

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

One-liner using the ternary operator ?:. If mode is 1 (truthy), perform the standard bitset operation by ORing with a shifted 1 bit. OR with 1 is always 1. If mode is 0 (falsy), perform the standard bitclear operation by ANDing with a shifted zero (shifting a 1 bit then inverting to create all 1s with a single zero). AND with 0 is always 0.

 

 

Was this helpful?
Upvote
Downvote