Set Baud Rate Field in Control Register

Code

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

#define BAUD_RATE_MASK (0xF << 8)

uint32_t set_baud_rate(uint32_t reg, uint8_t baud) {
    reg = ((baud & 0xF) << 8) | (reg & ~BAUD_RATE_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

 

This solution provides a function to set the baud rate in bits 8–11 of a 32-bit register. The macro BAUD_RATE_MASK defines the mask for these bits. The function set_baud_rate first clears bits 8–11 in the register, then sets them to the new baud value (ensuring only the lower 4 bits of baud are used). All other bits in the register remain unchanged. The main function reads the register and baud rate from input, applies the update, and prints the result. This approach ensures only the baud rate field is modified, preserving the integrity of other register fields.

 

 

Upvote
Downvote
Loading...

Input

0 10

Expected Output

2560