Search code examples
c++bit-manipulationbitsetstd-bitset

Bitwise OR on Bitset giving wrong answer


#include<bits/stdc++.h>
using namespace std;
int main(){
 bitset<5> num=01000;
 bitset<5> n=00000;
 bitset<5> result;
 result=(n|num);
 cout<<result;
}

Answer should be 1000 but it shows 00000


Solution

  • Binary literals have dedicated notion (since C++14): 0b01000 not 01000.

    #include <bitset>
    
    int main(int argc, char* argv[])
    {
        std::bitset<5> num = 0b01000;
        std::bitset<5> n = 0b00000;
        std::bitset<5> result;
    
        result = (n | num);
    
        std::cout << result << std::endl; // -> 01000
    
        return 0;
    }