Manipulating bitset in C++

2.3k views Asked by At

I was looking for some STL support for binary strings. bitset appears to be very useful, however I couldn't manipulate the individual bits sucessfully.

#include <iostream>
#include <bitset>

using namespace std;

int main()
{
    string b = bitset<8>(128).to_string();

    for(auto &x:b)
    {
        x = 1 and x-'0' ; cout<<b<<"\n";
    }

    return 0;
}

So, should I use vector or bitset can be used for manipulating individual bits ?

The above program gives:

☺0000000
☺ 000000
☺  00000
☺   0000
☺    000
☺     00
☺      0
☺

I know this happens because I am manipulating char, which when set to 0 prints the associated ascii character. My question is can I loop through a bitset and simultaneously modify the individual bits?

For example I surely can't do below :

#include <iostream>       
#include <string>         
#include <bitset>        
int main ()
{
  std::bitset<16> baz (std::string("0101111001"));
  std::cout << "baz: " << baz << '\n';

  for(auto &x: baz)

  {
      x = 1&x;

  }

std::cout << "baz: " << baz << '\n';

  return 0;
}
1

There are 1 answers

0
Ashot On BEST ANSWER

You can easily manipulate bits of std::bitset using set,reset,flip, operator[] methods. See http://www.cplusplus.com/reference/bitset/bitset/

// bitset::reset
#include <iostream>       // std::cout
#include <string>         // std::string
#include <bitset>         // std::bitset

int main ()
{
  std::bitset<4> foo (std::string("1011"));

  std::cout << foo.reset(1) << '\n';    // 1001
  std::cout << foo.reset() << '\n';     // 0000

  return 0;
}