Set or Clear a Specific Bit in a Register

Code

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

int main() // Changed to int for standard compliance
{
    uint8_t regval = 0, pos, ope;

    // Using %hhu for uint8_t to ensure memory safety
    if (scanf("%hhu %hhu %hhu", &regval, &pos, &ope) != 3) {
        return 1; 
    }

    if (1 == ope) 
    {
        regval |= (1 << pos); // Set bit
    } // Closed the IF block here
    else 
    {
        regval &= ~(1 << pos); // Clear bit
    }

    printf("%u\n", regval);
    
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

10 3 1

Expected Output

10