All submissions

Set or Clear a Specific Bit in a Register

Code

#include <stdio.h>

unsigned char modifyBit(unsigned char reg, int pos, int mode) {
    if(mode ==1 ){
        reg |= (1<<pos);   
    }
    else{
        
    reg &= ~(1 << pos);
    }
    return reg;
}

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

What is “setting” and “clearing” bits in a register?

A register in a microcontroller or CPU is a small piece of memory (usually 8, 16, or 32 bits) that controls hardware or stores status flags.
Each bit (0 or 1) inside the register often has a special meaning — turning on a feature, indicating a status, or controlling a pin.

  • Setting a bit → Changing it from 0 to 1 (enabling that feature/flag).
  • Clearing a bit → Changing it from 1 to 0 (disabling that feature/flag).
  • Toggling a bit → Flipping it (1 → 0, or 0 → 1).
  • Checking a bit → Reading whether it’s 1 or 0.

Why do we need this?

In embedded systems or low-level programming, many hardware devices are controlled by writing to their registers.

  • Each bit in the register might control a specific function.
  • Instead of rewriting the entire register, we modify only the bits we care about.
  • This prevents accidentally changing unrelated settings.

 

 

Loading...

Input

10 3 1

Expected Output

10