All submissions

Construct UART Data Frame with Parity Bit

Code

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

typedef struct {
    uint8_t parity_enable : 1;   // 0 = Disabled, 1 = Enabled
    uint8_t parity_type   : 1;   // 0 = Even parity, 1 = Odd parity
    uint8_t reserved      : 6;   // Reserved bits
} UART_Control;

uint8_t create_uart_frame(uint8_t data, UART_Control *ctrl) {
    data = data & 0x7F; // Ensure 7-bit data

    if (ctrl == NULL) {
        return data; // Safety check
    }

    if (ctrl->parity_enable == 0) {
        // Parity disabled → MSB=0, just return data
        return data;
    }

    // Count number of 1s in the 7-bit data
    int count = 0;
    int temp = data;
    while (temp) {
        count += (temp & 1);  // FIX: parentheses are important
        temp >>= 1;
    }

    // Compute parity bit
    uint8_t parity_bit;
    if (ctrl->parity_type == 0) {
        // Even parity: parity_bit = 1 if count is odd
        parity_bit = (count % 2 != 0);
    } else {
        // Odd parity: parity_bit = 1 if count is even
        parity_bit = (count % 2 == 0);
    }

    // Build final frame: MSB = parity bit
    uint8_t frame = (parity_bit << 7) | data;
    return frame;
}

int main() {
    uint8_t data;
    scanf("%hhu", &data);  // Read 0–127

    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

 

 

 

Loading...

Input

85 1 0

Expected Output

frame = 0x55