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) {
const uint8_t pos = 8;
    const uint8_t len = 4;
    
    // 2. Create a mask for 4 bits (0b1111)
    uint32_t mask = (1U << len) - 1;

    // 3. CLEAR the existing bits at positions 8-11
    // We shift the mask to position 8, invert it, and AND it with the register.
    reg &= ~(mask << pos);

    // 4. INSERT the new baud rate
    // We mask 'baud' to ensure it's only 4 bits, then shift it to position 8.
    uint32_t shifted_baud = (uint32_t)(baud & mask) << pos;

    // 5. Combine and return
    return reg | shifted_baud;
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

0 10

Expected Output

2560