在 C++ 中操作位集

adr*_*008 -2 c++ stl bitset

我正在寻找对二进制字符串的一些 STL 支持。bitset似乎非常有用,但是我无法成功地操作各个位。

#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;
}
Run Code Online (Sandbox Code Playgroud)

那么,我应该使用 vector 还是 bitset 来操作单个位?

上面的程序给出:

?0000000
? 000000
?  00000
?   0000
?    000
?     00
?      0
?
Run Code Online (Sandbox Code Playgroud)

我知道发生这种情况是因为我正在操作 char,当设置为 0 时会打印关联的 ascii 字符。我的问题是我可以遍历一个位集并同时修改单个位吗?

例如我肯定不能在下面做:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Ash*_*hot 6

您可以轻松地操作std::bitset使用set,reset,flip, operator[]方法的位。见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;
}
Run Code Online (Sandbox Code Playgroud)