1. Set or Clear a Specific Bit in a Register

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

// Set or clear a specific bit in an 8-bit register based
// on user input.
// If they send a 1 then we set
// if they send a 0 then we clear
unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    if (mode) {
        reg = reg | (1u << pos);
    }
    else {
        reg = reg & ~(1u << pos);
    }

    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

 

 

 

Was this helpful?
Upvote
Downvote