Set Baud Rate Field in Control Register

Code

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


/*
 * Cổ điển: Bài toàn thay các bit của `reg` tại [`pos`, `pos` + `len`) bằng `val` 
 * pos = 8, len = 4
 ***
 Clear tất cả các bit từ [8, 8 + 4):
    -> Tạo bit mask ((1 << len) - 1) << pos
    -> Clear: reg & ~(((1 << len) - 1) << pos)
 Set:
    -> Tạo bit mask (val & ((1 << len) - 1)) << pos;
*/
uint32_t set_baud_rate(uint32_t reg, uint8_t baud) {
    // Your code here

    reg &= ~(((1 << 4) - 1) << 8);
    reg |= (baud & ((1 << 4) - 1)) << 8;
    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

 

 

 

Upvote
Downvote
Loading...

Input

0 10

Expected Output

2560