How do I create a bitset from binary string?

George L picture George L · Jun 16, 2013 · Viewed 12.3k times · Source

I have a binary string in a file that looks like

0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001100100101101100110000110100110110111000010100110110110110111000011001000010110010010001100010010001010010010100001011001100010100001100100011011101

(which is 256 bits). Can I set this string as the value of a bitset<256> really quickly?

Currently I am doing

for (int t = sizeof(c) - 1; t > 0; t--) {
   if (c[t] == '1') {
      b |= 1;
   }
   b <<= 1;
}
b >>= 1;

But my results are incorrect.

Answer

Shafik Yaghmour picture Shafik Yaghmour · Jun 16, 2013

Can I set this string as the value of a bitset<256> really quickly?

Yes, you can just use the constructor, the example below is taken right from the document and works for 256 as well:

std::string bit_string = "110010";
std::bitset<8> b3(bit_string);       // [0,0,1,1,0,0,1,0]

std::cout << b3.to_string() << std::endl ;