Bit Operations using Macros

Code

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

// Define bitwise macros here
#define BIT_SET(reg,pos) (reg |= (1 << pos));
#define BIT_CLEAR(reg, pos) (reg &= ~(1 << pos));
#define BIT_TOGGLE(reg, pos) (reg ^= (1 << pos));  

void printBinary(uint8_t x); 

uint8_t modify_register(uint8_t reg) {
    //printBinary(reg);
    BIT_SET(reg,2);
    //printBinary(reg);
    BIT_SET(reg,7);
    //printBinary(reg);
    BIT_CLEAR(reg,3)
    //printBinary(reg);
    BIT_TOGGLE(reg, 5);
    //printBinary(reg);
    return reg;
}

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


//FUNCTION TO PRINT BINARY 8 bit
void printBinary(uint8_t x){
    //1. Find size of passed int
    int num_bits = sizeof(x)*8;
    //2. loop through every bit and perform checkbit
    //printf("Int value is: %hhu, Num of bits is: %d\n",x, num_bits);
    for(int i=num_bits-1;i>=0;i--){
    //Prints a space every 4 bits
    if ((i+1)%4==0 && i+1 != sizeof(x)*8){
        printf(" ");
    }
    if (x & (1 << i)){
        printf("1");
    } 
    else{
        printf("0");
    }
    }
    printf("\n");
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Expected Output

164