Bit Operations using Macros

Code

#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
    SET_BIT(reg ,2); SET_BIT(reg,7);
    CLEAR_BIT(reg,3);
    TOGGLE_BIT(reg,5);
    return reg;
}

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

Solving Approach

Got to know the usage of macros

 

#define SET_BIT(r,b)  ((r) |=(1U<<(b)))

  1. define must be written in lowercase.
  2. Macros always to be defined in uppercase.
  3. When defining logic for a macro, we enclose each argument in a bracket.
  4. NO SPACE BETWEEN THE macro_definition and its arguments. (The arguments for using a macro should be defined just like a function)

 

 

Upvote
Downvote
Loading...

Input

0

Expected Output

164