Byte Buffer Indexing

#include <iostream>
#include <cstdint>

using namespace std;

class ByteBuffer {
private:
    // Internal storage for exactly 8 bytes
    uint8_t data[8];

public:
    /**
     * Overloaded subscript operator.
     * By returning uint8_t& (a reference), we allow the caller
     * to both read from and write to the internal 'data' array.
     */
    uint8_t& operator[](int index) {
        return data[index];
    }

    /**
     * Const version of the operator.
     * This is good practice to allow read-only access if 
     * the ByteBuffer object itself is marked as const.
     */
    uint8_t operator[](int index) const {
        return data[index];
    }
};

int main() {
    ByteBuffer buffer;

    // Reading 8 initial values
    for (int i = 0; i < 8; i++) {
        int x;
        cin >> x;
        // This calls the overloaded operator[] to store the value
        buffer[i] = static_cast<uint8_t>(x);
    }

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

    // This calls the overloaded operator[] to update a specific byte
    buffer[idx] = static_cast<uint8_t>(v);

    // Printing the final state of the buffer
    for (int i = 0; i < 8; i++) {
        // Casting to (int) is necessary because cout treats 
        // uint8_t (unsigned char) as a character instead of a number.
        cout << (int)buffer[i] << (i == 7 ? "" : " ");
    }
    cout << endl;

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

1 2 3 4 5 6 7 8 3 99

Expected Output

1 2 3 99 5 6 7 8