76. Construct UART Data Frame with Parity Bit

Back To All Submissions
Previous Submission
Next Submission

Code

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

// #define CLEAR_BIT(data, pos) (~(1<<pos) & data)

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

int get_parity_sum(uint8_t data){
    int sum = 0;
    for (size_t i=0; i<8; i++){
        if (data & 1<<i){
            sum++;
        }
    }
    return sum;
}

uint8_t create_uart_frame(uint8_t data, UART_Control *ctrl) {
    // Your logic here
    uint8_t new_data = 0;
    uint8_t pmask = 0;

    if ((*ctrl).parity_enable){
        bool p_even = (get_parity_sum(data) % 2) == 0;
        if ((*ctrl).parity_type){
            pmask = p_even ? 1 : 0;
        } else {
            pmask = p_even ? 0 : 1;
        }
    }
    new_data = new_data | pmask<<7;
    new_data = new_data | data;
    return new_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

 

 

 

Was this helpful?
Upvote
Downvote