Set or Clear a Specific Bit in a Register

Solving Approach

#include <stdio.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    //Initialise a variable for storing the result
    unsigned char result = 0;

    //Check for mode '1'
    if(mode) result = reg | (1 << pos);

    //Check for mode '0'
    else result = reg & ~(1 << pos);

    //Return the result
    return result;
}

int main() {
    unsigned char reg;
    int pos, mode;
    scanf("%hhu %d %d", &reg, &pos, &mode);
    printf("%d", modifyBit(reg, pos, mode));
    return 0;
}

 

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10