8

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.

2
  • Are you sure t=sizeof(c)-1 is correct? What is sizeof(c)? Commented Jun 16, 2013 at 1:21
  • 1
    Yes, there's a constructor for that. Commented Jun 16, 2013 at 1:27

2 Answers 2

10

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 ;
Sign up to request clarification or add additional context in comments.

Comments

1

Why not access the by indices directly? like..

b[t] = c[t] - '0';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.