Set or Clear a Specific Bit in a Register

Code

#include <stdio.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    // Write your code here 00001010
    /* 
    Step by step process
    1. I need to take the register value and focus on the specific bit position
    2. I need to set that bit position to 1 or 0 depending on the mode
    3. return the register value after completing all of that
    */

    if(mode){
    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

 

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10