78. UART Frame Builder

#include <iostream>
#include <cstdint>
using namespace std;

class Frame {
private:
    uint8_t buffer[16];
    int size;

public:
    Frame() : size(0) {}

    // Append a byte to the frame
    Frame& operator+=(uint8_t byte) {
        if (size < 16) {
            buffer[size++] = byte;
        }
        return *this;
    }

    // Read-only indexed access
    uint8_t operator[](int index) const {
        return buffer[index];
    }

    int getSize() const {
        return size;
    }
};

int main() {
    int n;
    cin >> n;

    Frame frame;

    for (int i = 0; i < n; i++) {
        int b;
        cin >> b;
        frame += (uint8_t)b;
    }

    for (int i = 0; i < frame.getSize(); i++) {
        cout << (int)frame[i];
        if (i + 1 < frame.getSize()) {
            cout << " ";
        }
    }

    return 0;
}

Explanation & Logic Summary

  • operator+= appends a single byte to the frame while enforcing the 16-byte limit
  • operator[] provides indexed access for reading frame contents
  • uint8_t ensures byte-accurate storage consistent with hardware registers
  • A fixed-size buffer avoids heap usage, which is critical in embedded firmware

Firmware Relevance & Real-World Context

This problem mirrors real embedded communication workflows, including:

  • UART transmit buffers
  • SPI and I2C message assembly
  • CAN and Modbus payload construction
  • Register-level driver development

Using operator+= enables expressive and readable firmware code:

frame += header;
frame += command;
frame += payload;

This pattern is commonly used in Embedded C++ drivers to combine safety, clarity, and hardware-aware constraints, making it highly relevant for real-world firmware development.

 

 

 

 

Loading...

Input

4 10 20 30 40

Expected Output

10 20 30 40