Set or Clear a Specific Bit in a Register

Code

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

int main()
{
    uint8_t reg;   // 8-bit register
    uint8_t pos;   // bit position (0–7)
    uint8_t mode;  // 1 = set, 0 = clear

    // Input
    scanf("%hhu", &reg);
    scanf("%hhu", &pos);
    scanf("%hhu", &mode);

    // Operation
    if(mode == 1)
    {
        reg = reg | (1 << pos);   // SET bit
    }
    else if(mode == 0)
    {
        reg = reg & ~(1 << pos);  // CLEAR bit
    }

    // Output
    printf("%u\n", reg);

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10