61. Bit Operations using Macros

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

#define SET_BIT(r, b)    ((r) |= (1 << (b)))
#define CLEAR_BIT(r, b)  ((r) &= ~(1 << (b)))
#define TOGGLE_BIT(r, b) ((r) ^= (1 << (b)))

uint8_t modify_register(uint8_t reg) {
    SET_BIT(reg, 2);      // Set bit 2
    SET_BIT(reg, 7);      // Set bit 7
    CLEAR_BIT(reg, 3);    // Clear bit 3
    TOGGLE_BIT(reg, 5);   // Toggle bit 5
    return reg;
}

int main() {
    uint8_t reg;
    scanf("%hhu", &reg);
    printf("%u", modify_register(reg));
    return 0;
}

What is this about?

This simulates real-world register modification in firmware, where operations like setting an enable bit, clearing an interrupt flag, or toggling a mode bit are done with care.

Why it’s important in firmware?

  • A single incorrect bit can misconfigure hardware
  • Bitwise macros improve readability and reduce human error
  • Used everywhere in GPIO config, interrupts, control/status logic
     

Solution Logic

  • Use OR (|=) to set
  • Use AND with NOT (&= ~) to clear
  • Use XOR (^=) to toggle
     
Loading...

Input

0

Expected Output

164