Playing with bits

Here is a few handy tricks to manipulate bits in multibit values

  • Setting a bit number n in a value x
    int val = 122;
    std::bitset<8> a(val);
    std::cout << a << std::endl; //01111010
    // setting bit number 2 to 1
    a |= (1 << 2);
    std::cout << a << std::endl; //01111110
  • Twiddling a bit number n in a value x
    std::bitset<8> a(val); //01111010
    a &= ~(1 << 2); //01111010
0