77. Byte Buffer Indexing

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

class ByteBuffer {
private:
    uint8_t data[8];

public:
    uint8_t& operator[](int index) {
        return data[index];
    }

    uint8_t operator[](int index) const {
        return data[index];
    }
};

int main() {
    ByteBuffer buffer;

    for (int i = 0; i < 8; i++) {
        int x;
        cin >> x;
        buffer[i] = static_cast<uint8_t>(x);
    }

    int idx, v;
    cin >> idx >> v;

    buffer[idx] = static_cast<uint8_t>(v);

    for (int i = 0; i < 8; i++) {
        cout << (int)buffer[i] << (i == 7 ? "" : " ");
    }

    return 0;
}

Explanation & Logic Summary:

  • operator[] returns a reference to enable assignment
  • uint8_t models real firmware byte buffers
  • Explicit value constraints eliminate overflow ambiguity
  • Casting to int ensures correct numeric output

Firmware Relevance & Real-World Context:

Byte buffers are fundamental in embedded systems:

  • UART / SPI / I²C frames
  • CAN payloads
  • Sensor data packets
  • DMA buffers
  • Command parsing

Operator overloading provides clean syntax without runtime overhead and reflects real embedded abstractions.

 

 

 

 

Loading...

Input

1 2 3 4 5 6 7 8 3 99

Expected Output

1 2 3 99 5 6 7 8