45. Serialized Data Buffer

Back To All Submissions
Previous Submission
Next Submission

Code

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

void build_packet(uint8_t command, uint16_t value, uint8_t status, uint32_t checksum) {
    uint8_t buffer[10];

    // Your logic to fill buffer
    buffer[0] = 0xA5;
    buffer[1] = command;
    //How to seperate uint16 value into 2 bytes?
    //Method 1 (Pointer casting):
    //Method 2 (Bit manipulation & masking with 0xFF)
    // 1. Cast the address to a uint8_t pointer
    uint8_t *bytePtr = (uint8_t *)&value;

    // 2. Access the bytes
    uint8_t lowByte = bytePtr[0];  // Lower address
    uint8_t highByte = bytePtr[1]; // Higher address
    buffer[2] = lowByte;
    buffer[3] = highByte;
    buffer[4] = status;
    //How to seperate uint32 value into 4 seperate bytes?
    //"Create a 8 bit pointer that points to checksum (split up as bytes)"
    uint8_t *checksumBytePtr = (uint8_t *)&checksum;
    buffer[5] = checksumBytePtr[0];
    buffer[6] = checksumBytePtr[1];
    buffer[7] = checksumBytePtr[2];
    buffer[8] = checksumBytePtr[3];
    buffer[9] = 0x5A;
    
    //LSByte first then MSB of 16bit value
    // 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

 

 

 

Was this helpful?
Upvote
Downvote