12. Register Representation 8-bit

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

class Register8 {
private:
    unsigned char value;

public:
    Register8() : value(0) {}

    void setBit(int pos) {
        value |= static_cast<unsigned char>(1u << pos);
    }

    void clearBit(int pos) {
        value &= static_cast<unsigned char>(~(1u << pos));
    }

    void toggleBit(int pos) {
        value ^= static_cast<unsigned char>(1u << pos);
    }

    unsigned char getValue() const {
        return value;
    }
};

int main() {
    Register8 reg;
    int n;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        string op;
        int pos;
        cin >> op >> pos;
        if (op == "set") {
            reg.setBit(pos);
        } else if (op == "clear") {
            reg.clearBit(pos);
        } else if (op == "toggle") {
            reg.toggleBit(pos);
        }
    }
    cout << (int)reg.getValue();
    return 0;
}

 

Solution Details

  • The register value is stored as an 8-bit byte (unsigned char) and initialized to 0.
  • Bit operations use masks:
    • set: OR with 1 << pos sets the target bit.
    • clear: AND with the inverse mask clears the target bit.
    • toggle: XOR with 1 << pos flips the bit.
  • Returning unsigned char mirrors an actual 8-bit hardware register; casting to int is only for printing.

Significance for Embedded Developers: This models a GPIO/control register abstraction. By confining updates to methods, you reduce the risk of corrupting reserved bits and create a reusable, testable unit that mirrors how HALs manage hardware registers.
 

Loading...

Input

3 set 0 set 2 toggle 2

Expected Output

1