75. Pointer to Struct with Bitfields

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

struct UART_ControlRegister {
    unsigned int baudrate : 4;   // Bits 0-3
    unsigned int tx_enable : 1;  // Bit 4
    unsigned int rx_enable : 1;  // Bit 5
    unsigned int tx_irq_en : 1;  // Bit 6
    unsigned int rx_irq_en : 1;  // Bit 7
    unsigned int parity_en : 1;  // Bit 8
    unsigned int stop_bits : 1;  // Bit 9
    unsigned int reserved : 22;  // Bits 10-31
};

// Hàm nhận vào con trỏ cấu trúc
void configure_uart(struct UART_ControlRegister *reg) {
    // 1. Thiết lập các giá trị theo yêu cầu
    reg->baudrate = 9;
    reg->tx_enable = 1;
    reg->rx_enable = 1;
    reg->tx_irq_en = 1;
    reg->rx_irq_en = 0;
    reg->parity_en = 1;
    reg->stop_bits = 0;

    // 2. In giá trị để kiểm tra
    printf("baudrate = %u\n", reg->baudrate);
    printf("tx_enable = %u\n", reg->tx_enable);
    printf("rx_enable = %u\n", reg->rx_enable);
    printf("tx_irq_en = %u\n", reg->tx_irq_en);
    printf("rx_irq_en = %u\n", reg->rx_irq_en);
    printf("parity_en = %u\n", reg->parity_en);
    printf("stop_bits = %u\n", reg->stop_bits);
}

int main() {
    // Tạo một thực thể struct thực sự trong bộ nhớ
    struct UART_ControlRegister myUart = {0}; 

    // Truyền địa chỉ của struct vào hàm
    configure_uart(&myUart);

    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote