Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Wrong result when XOR'ing two std::bitset

#include <bitset>
#include <iostream>

int main() {
    std::bitset<8> a = 10101010;
    std::bitset<8> b = 11111111;

    std::cout << (a ^ b);
}

When running the following code the result is:

11010101

Expected output is:

01010101

Am I doing something wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You initialize a and b with values which are int literals.

In order to use binary literals you need the 0b prefix:

#include <bitset>
#include <iostream>

int main() {
    std::bitset<8> a = 0b10101010;
    std::bitset<8> b = 0b11111111;

    std::cout << (a ^ b);
}

Output:

01010101

Live demo

More info about such literals: Integer literal.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading