10. Bit Operations using Macros

Discussions3
Log in to post comments and replies.
You
Loading editor...
KangajanKuganathan
#include <stdio.h>
#include <stdint.h>

// Define bitwise macros here
#define SET_BIT(reg, bit)     ((reg) |= (1U << (bit)))
#define CLEAR_BIT(reg, bit)   ((reg) &= ~(1U << (bit)))
#define TOGGLE_BIT(reg, bit)  ((reg) ^= (1U << (bit)))

uint8_t modify_register(uint8_t reg) {
    // Apply operations in order
    //1. set 2 and 7 bits
    SET_BIT(reg, 2);
    SET_BIT(reg, 7);
    //2. clear 3rd bit
    CLEAR_BIT(reg, 3);
    //3. Toggle 5th bit
    TOGGLE_BIT(reg, 5);
    return reg;
}

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

yo can anyone help me im learning embedded c and have no idea or sources where to study from is this website good enough?

 

0
NordinSutkovic
NordinSutkovic
Aug 01 2026

looks good so far

-1
lokeshloki6870
lokeshloki6870
Jul 30 2026
#include <stdio.h>
#include <stdint.h>

// Define bitwise macros here

uint8_t modify_register(uint8_t reg) {
    // Apply operations in order
    /*reg = reg | (1<<2);
    reg = reg |(1<<7);
    reg = reg & ~(1<<3);
    reg = reg ^(1<<5);
    return reg;*/
    return (((reg | (1<<2) | (1<<7)) &~(1<<3)) ^(1<<5));
}

int main() {
    uint8_t reg;
    scanf("%hhu", &reg);
    printf("%u", modify_register(reg));
    return 0;
} 
 We can also do like this 
0