8-Bit Register Class

#include <iostream>
#include <cstdint>

using namespace std;

class Reg8 {
private:
    // Private member to store the 8-bit value
    uint8_t value;

public:
    // Constructor: Initializes the register to 0
    Reg8() : value(0) {}

    // Writes a new 8-bit value to the register
    void write(uint8_t v) {
        value = v;
    }

    // Returns the current 8-bit value
    uint8_t read() const {
        return value;
    }

    // Sets a specific bit (0-7) to 1 using the OR operator
    void setBit(int bit) {
        if (bit >= 0 && bit <= 7) {
            value |= (1 << bit);
        }
    }

    // Clears a specific bit (0-7) to 0 using the AND and NOT operators
    void clearBit(int bit) {
        if (bit >= 0 && bit <= 7) {
            value &= ~(1 << bit);
        }
    }
};

int main() {
    int initialValue;
    int bitToSet, bitToClear;

    // Reading inputs
    if (!(cin >> initialValue >> bitToSet >> bitToClear)) return 0;

    Reg8 reg;
    
    // 1. Load the initial value
    reg.write(static_cast<uint8_t>(initialValue));
    
    // 2. Set the requested bit
    reg.setBit(bitToSet);
    
    // 3. Clear the requested bit
    reg.clearBit(bitToClear);

    // 4. Output the final state as an integer
    cout << static_cast<int>(reg.read()) << endl;

    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

10 1 3

Expected Output

2