Set Baud Rate Field in Control Register

Code

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

uint32_t set_baud_rate(uint32_t reg, uint8_t baud) {
    // 1. Create a mask for 4 bits (0xF is 1111 in binary)
    // 2. Shift it to the starting position (bit 8)
    uint32_t mask = (0xF << 8);

    // 3. Clear the bits 8-11 in the register using AND with the inverse mask
    reg &= ~mask;

    // 4. Mask the input baud to ensure it's only 4 bits, shift it, and OR it into reg
    reg |= ((uint32_t)(baud & 0xF) << 8);

    return reg;
}

int main() {
    uint32_t reg;
    uint8_t baud;
    // Note: Using %u for uint32_t and %hhu for uint8_t
    if (scanf("%u %hhu", &reg, &baud) == 2) {
        printf("%u\n", set_baud_rate(reg, baud));
    }
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

0 10

Expected Output

2560