23. Set Baud Rate Field in Control Register

Back To All Submissions
Previous Submission
Next Submission

Code

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

uint32_t set_baud_rate(uint32_t reg, uint8_t baud) {
    // Your code here
    // First, we need to clear the bits 8-11 controlling the baud rate
    uint32_t clear_mask = 0b1111;
    clear_mask = ~(clear_mask << 8);
    reg &= clear_mask;
    // Next we replace the bits 8-11 with the baud bits
    uint32_t set_mask = baud << 8;
    reg |= set_mask;
    return reg;
}

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

Solving Approach

First clear the baud bits (8-11), with & operator on an inverse mask.

Then set the baud bits by using OR with the baud bits.

 

 

Was this helpful?
Upvote
Downvote