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) {
    // Your code here
    reg |= (1 << pos);
    return reg;
}

int main() {
    uint8_t reg, pos;
    scanf("%hhu %hhu", &reg, &pos);  // Accept register value and position
    uint8_t result = set_bit(reg, pos);
    printf("%u", result);         // Output the result as an integer
    return 0;
}

Solving Approach

In C, bitwise operations allow direct manipulation of individual bits within a byte, word, or register. These operations are performed using the following operators:

  • | → Bitwise OR — typically used to set a bit
  • & → Bitwise AND — used to clear or check a bit
  • ^ → Bitwise XOR — used to toggle (invert) a bit
  • ~ → Bitwise NOT — used to flip all bits (1 to 0, 0 to 1)
  • << >> → Bit shift left/right — used to move bit positions
     

Common bit-masking patterns:

reg |= (1 << n);     // Set bit n
reg &= ~(1 << n);    // Clear bit n
reg ^= (1 << n);     // Toggle bit n
if (reg & (1 << n))  // Check if bit n is set

These operations are used to target and modify only specific bits, without disturbing others.

8-bit Visualization Example

Bit

7

6

5

4

3

2

1

0

Value1286432168421

E.g.

To set bit 3 → reg |= (1 << 3)
To clear bit 6 → reg &= ~(1 << 6)
To check bit 0 → reg & (1 << 0)
To toggle but 3 → reg ^= (1 << 3)

 

Upvote
Downvote
Loading...

Input

5 1

Expected Output

7