C++ bitset strange value

168 Views Asked by At
#include <bitset>
#include <assert.h>
#include <stdio.h>
using namespace std;


int main()
{
    bitset<128> bs(42);
    bs[11]=0;
    bs[12]=1;
    assert(bs[12]==1);
    printf("bs[11]=%d\n", bs[11]);
    printf("bs[12]=%d\n", bs[12]);
    return 0;
}

console output: enter image description here

Why can't I simply get 0 or 1 as output ?

3

There are 3 best solutions below

3
wohlstad On BEST ANSWER

printf with %d is for integer values, whereas std::bitset::operator[] returns a std::bitset::reference.

You can use std::cout from <iostream> header (which is anyway a more c++ "way" to print to the console):

#include <bitset>
#include <assert.h>
#include <iostream>

int main()
{
    std::bitset<128> bs(42);
    bs[11] = 0;
    bs[12] = 1;
    assert(bs[12] == 1);
    std::cout << "bs[11]=" << bs[11] << std::endl;
    std::cout << "bs[12]=" << bs[12] << std::endl;
    return 0;
}

Output:

bs[11]=0
bs[12]=1

A side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.

3
Jean-Baptiste Yunès On

If you are using C++ then don't call printf to output something (my compiler refuse to compile your code correctly). This C++ code works correctly using iostream:

#include <bitset>
#include <iostream> 

int main()
{
    std::bitset<128> bs(42);
    bs[11]=0;
    bs[12]=1;
    std::cout << "bs[11]=" << bs[11] << std::endl;
    std::cout << "bs[12]=" << bs[12] << std::endl;
    return 0;
}
0
Pepijn Kramer On

With some review comments :

#include <cassert>
#include <bitset>
#include <iostream>

// anything with a .h extension is probably "C" not "C++"
// #include <assert.h>
//#include <stdio.h>
// using namespace std; <== NO, don't use using namespace std;

int main()
{
    std::bitset<128> bs(42);
    bs[11]=0;
    bs[12]=1;

    assert(bs[12]==1);

    std::cout <<"bs[11]" << bs[11] << "\n";
    std::cout << "bs[12]" << bs[11] << "\n";

    return 0;
}