All submissions

Set or Clear a Specific Bit in a Register

Code

#include <stdio.h>
/*
Plan:
- Create a mask for the position using left shift
- Clear the bit at the position
- Or the mode bit at the position

Example:
input -> reg = 0xA -> 00001010
output -> 00001010

0000_010
shift the mode to the third position
or it with the masked reg


*/
unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    // Write your code here
    unsigned char output = 0;
    unsigned char mask = reg & ~(1U<<pos);
    output = mask | (mode<<pos);

    return output; 
}

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

 

 

 

Loading...

Input

10 3 1

Expected Output

10