38. Toggle Bitmask

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

class Flags {
private:
    uint8_t bits;
public:
    Flags(uint8_t b) : bits(b) {}

    Flags operator~() const {
        return Flags(~bits);
    }

    uint8_t getBits() const {
        return bits;
    }
};

int main() {
    int val;
    cin >> val;

    Flags f(val);
    Flags toggled = ~f;

    cout << "Toggled=" << (int)toggled.getBits();

    return 0;
}

Solution Details

  • The operator ~ is overloaded to return a new Flags object with bits inverted.
  • Because bits is uint8_t, inversion stays within 8 bits.
     

👉 In simple words:
 Normally ~ flips all the bits of an integer. By overloading it, we allow ~ to work directly on a custom class like Flags.

 

Significance for Embedded Developers

  • Bitmasks are used in registers and configuration flags.
  • Being able to flip all bits with ~ on a class makes code clean and closer to how hardware is manipulated.
  • Example: flipping an enable/disable mask for GPIO or communication flags.
     
Loading...

Input

0

Expected Output

Toggled=255