Construct UART Data Frame with Parity Bit

Code

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

typedef struct {
    uint8_t parity_enable : 1;
    uint8_t parity_type   : 1;
    uint8_t reserved      : 6;
} UART_Control;

uint8_t create_uart_frame(uint8_t data, UART_Control *ctrl) {
    // chỉ lấy 7 bit thấp
    data &= 0x7F;

    // nếu KHÔNG dùng parity
    if (ctrl->parity_enable == 0) {
        // bit 7 = 0, 7 bit thấp = data
        return data;
    }

    // nếu CÓ dùng parity → tính parity bit
    uint8_t ones = 0;

    // đếm số bit 1 trong 7 bit data
    for (int i = 0; i < 7; i++) {
        if (data & (1 << i)) {
            ones++;
        }
    }

    uint8_t parity_bit;

    if (ctrl->parity_type == 0) {
        // EVEN parity
        // data có số bit 1 lẻ → parity = 1
        // data có số bit 1 chẵn → parity = 0
        parity_bit = ones % 2;
    } else {
        // ODD parity
        // data có số bit 1 chẵn → parity = 1
        // data có số bit 1 lẻ → parity = 0
        parity_bit = !(ones % 2);
    }

    // ghép parity bit vào bit 7
    return (parity_bit << 7) | data;
}

int main() {
    uint8_t data;
    scanf("%hhu", &data);  // 7-bit input

    uint8_t parity_enable, parity_type;
    scanf("%hhu %hhu", &parity_enable, &parity_type);

    UART_Control ctrl;
    ctrl.parity_enable = parity_enable;
    ctrl.parity_type = parity_type;

    uint8_t frame = create_uart_frame(data, &ctrl);
    printf("frame = 0x%02X", frame);

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

85 1 0

Expected Output

frame = 0x55