Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a bitset from binary string?

Tags:

c++

char

bitset

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.

like image 845
George L Avatar asked Jun 16 '13 01:06

George L


2 Answers

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 ;
like image 106
Shafik Yaghmour Avatar answered Sep 18 '22 23:09

Shafik Yaghmour


Why not access the by indices directly? like..

b[t] = c[t] - '0';
like image 23
Annie Kim Avatar answered Sep 17 '22 23:09

Annie Kim