Write-1-to-Clear Flag Encapsulation

#include <iostream>
#include <iomanip>
#include <cstdint>

class StatusRegister {
private:
    // Simulates the hardware bus write operation
    // DO NOT MODIFY THIS FUNCTION
    void busWrite(uint32_t val) {
        std::cout << "Write: 0x" 
                  << std::hex << std::uppercase << std::setw(8) << std::setfill('0') 
                  << val << std::endl;
    }

public:
    /**
     * Clears a hardware flag using W1C logic.
     * @param bit_index The position (0-31) of the flag to clear.
     */
    void clearFlag(int bit_index) {
        // 1. Create a mask with a 1 at the bit_index.
        // We use 1ULL or static_cast to ensure we are working with unsigned 32-bit logic.
        uint32_t mask = static_cast<uint32_t>(1) << bit_index;

        // 2. Write the mask directly to the bus.
        // This avoids the Read-Modify-Write bug because we aren't reading 
        // existing bits and writing them back.
        busWrite(mask);
    }
};

int main() {
    int N;
    // Standard check for input count
    if (!(std::cin >> N)) return 0;

    StatusRegister driver;

    for (int i = 0; i < N; ++i) {
        int bit_idx;
        // Read the target bit to clear from the user/test-case
        if (std::cin >> bit_idx) {
            // Call the encapsulated W1C logic
            driver.clearFlag(bit_idx);
        }
    }

    return 0;
}

Solving Approach

 

 

 

 

 

Upvote
Downvote
Loading...

Input

3 0 4 31

Expected Output

Write: 0x00000001 Write: 0x00000010 Write: 0x80000000