Serialized Data Buffer

Code

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

void split_bytes(uint8_t number_of_bytes, uint32_t reg, uint8_t* byte){
    uint32_t mask = ((1<<8) - 1);
    for(uint8_t i=0; i<number_of_bytes; i++){
        byte[i] = (reg >> 8*i) & (mask);
    }
}

void build_packet(uint8_t command, uint16_t value, uint8_t status, uint32_t checksum) {
    uint8_t buffer[10];
    uint8_t byte_val[2];
    uint8_t byte_check[4];
    uint8_t start = 0xA5;
    uint8_t end = 0x5A;
    // Your logic to fill buffer
    buffer[0]=start;
    buffer[9]=end;
    buffer[1]=command;
    buffer[4]=status;
    split_bytes(2, value, byte_val);
    buffer[2] = byte_val[0];
    buffer[3] = byte_val[1];
    split_bytes(4, checksum, byte_check);
    for(int i=0; i<4; i++){
        buffer[5+i] = byte_check[i];
    }
    // Then print buffer
    for(int i=0; i<10; i++){
        printf("%d ", buffer[i]);
    }
}

int main() {
    uint8_t cmd, status;
    uint16_t val;
    uint32_t crc;

    scanf("%hhu %hu %hhu %u", &cmd, &val, &status, &crc);
    build_packet(cmd, val, status, crc);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

1 4660 1 2864434397

Expected Output

165 1 52 18 1 221 204 187 170 90