Set the Bit in an 8-bit Register

Code

#include <stdio.h>
#include <stdint.h>

uint8_t set_bit(uint8_t reg, uint8_t pos) {
    return reg | (1 << pos);
}

int main() {
    uint8_t reg, pos;
    scanf("%hhu %hhu", &reg, &pos);
    uint8_t result = set_bit(reg, pos);
    printf("%u", result);
    return 0;
}

Solving Approach
 

  • Create a bit mask by left-shifting 1 to the required position:1 << pos.
  • This mask has 1only at the target bit and 0 elsewhere.
  • Use bitwise OR (|) with the register to force that bit to 1.
  • OR keeps all other bits unchanged while setting the required bit.

 

Upvote
Downvote
Loading...

Input

5 1

Expected Output

7