Bit Operations using Macros

Code

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

// Define bitwise macros here

uint8_t modify_register(uint8_t reg) {

    // Apply operations in order
    reg |= 1<<2; //set bit 2 
    reg |= 1<<7;// set bit 7
    reg &= ~(1<<3); // Clear bit 3
    reg ^= (1<<5); //Toggle bit 5

    return reg;
}

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

Solving Approach

Read-Modify-Write. By using |=, &=, and ^=, you are reading the current value, changing only the bit you care about, and writing it back. If you just use =, you destroy all the other settings in that register!

A Quick Challenge to boost your confidence:

How would you write the code to Set bit 0 and bit 1 at the same time using only one line of code?

(Hint: You can OR the masks together like this: (1<<0) | (1<<1))

 

 

Upvote
Downvote
Loading...

Expected Output

164