129. Write-1-to-Clear Flag Encapsulation

In many embedded microcontrollers (e.g., STM32, AVR), hardware interrupt flags in Status Registers operate on a "Write-1-to-Clear" (W1C) logic.

  • To clear a specific flag, firmware must write a 1 to that bit position.
  • Writing 0 to a bit has no effect.

A common bug occurs when developers use standard "Read-Modify-Write" logic (e.g., reg &= ~mask) to clear flags. This is dangerous because reading the register might capture other pending flags, and writing them back as 1 (if the read value is preserved) will accidentally clear those unhandled interrupts.

Your task is to encapsulate this logic in a StatusRegister class:

  • Implement a clearFlag method that accepts a bit_index.
  • Construct a mask with a 1 only at the specified position.
  • Write this mask directly to the simulated hardware bus using the provided busWrite() function.
  • Do NOT read the current register state.
  • Do NOT use bitwise AND/NOT (&= ~) operators.

Program Flow:

  1. Initialize a StatusRegister instance.
  2. Read an integer N (number of operations).
  3. Loop N times:
  4. Read an integer bit_index (the flag to clear).
  5. Call driver.clearFlag(bit_index).
  6. The busWrite function (internal simulation) prints the value written to the bus.

Input Format:

  • First line: Integer N (number of test inputs).
  • Next N lines: Integer bit_index (0 to 31).
  • Input is provided via standard input (stdin).

Output Format:

  • For each operation, the busWrite function prints the hex value being written.
  • Format: Write: 0x<8-digit-HEX>
  • Each output must be on a new line.

Example: 

Example 1

Input:

3
0
4
31

Output:

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

Constraints:

  • N range: 1 to 20
  • bit_index range: 0 to 31
  • Do NOT use Read-Modify-Write operations (e.g., |=, &=)
  • Must use bitwise shifting to generate masks
  • No dynamic memory allocation

 

 

Loading...

Input

3 0 4 31

Expected Output

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