Lynob
Lynob

Reputation: 5327

C++: About inserting in bitset

Using STD bitset. I'm converting a sting to binary using this answer. If I do this it works

string myString = "Hi";
for ( int i = 0; i < myString.size(); ++i)
  {
 cout << bitset<8>(myString.c_str()[i]) << endl;
}

If I do this it works

string myString = "Hi";
for ( int i = 0; i < myString.size(); ++i)
  {
 cout << bitset<8>foo(myString.c_str()[i]) << endl;
}

But this doesn't work, I want to know why

string myString = "Hi";
bitset<8>foo;

for ( int i = 0; i < myString.size(); ++i)
  {
 cout <<foo(myString.c_str()[i]) << endl;
}

I getno match for call to ‘(std::bitset<8>) (const char&)’

I think I know how to fix it, but I don't understand why is this happening? Can't you insert into bitset after declaration?

Lets try one more time, something like this would work

for (std::size_t i = 0; i < myString.size(); ++i)
  {
   bitset<8>bar(myString.c_str()[i]);
   foo[i] = bar[i];
  }

Now this works but only 8 bits exits in foo and everything is correct in bar plus I don't like it, it seems to much code.

All I want is to declare foo and then insert bits to it in the loop, what am I missing? I don't want to use any third party library.

Upvotes: 2

Views: 1587

Answers (2)

Killzone Kid
Killzone Kid

Reputation: 6240

I want to convert to base 2 then store in a dynamically allocated bitset or vector. I prefer to keep everything in bitsets

vector of bitsets

#include <iostream>
#include <string>
#include <vector>
#include <bitset>

int main()
{
    std::string myString = "Hi";
    std::vector<std::bitset<8>> vec;

    // populate vector
    for (std::bitset<8> foo : myString)
        vec.emplace_back(foo);

    // print vec content
    for (auto const &bits : vec)
        std::cout << bits << std::endl;

    return 0;
}

https://ideone.com/OkAGF2

If you want bitset to be converted to string you can do so using bitset .to_string() method

Upvotes: 1

Sebastian Redl
Sebastian Redl

Reputation: 71899

It's the difference between the type(arguments) syntax, which uses a constructor to create an object, and the value(arguments) syntax, which calls a function or call-operator of an object.

bitset has a constructor that takes an integral type, but it does not have a a call operator.

I don't understand the overall goal, though. If you want to write out the bits of every character, the first method works. (The second snippet does not compile.) What do you hope to achieve with the third snippet that's different? If you want to collect all the bits of all the characters, your bitset isn't large enough; it only has space for 8 bits.

On a side note, s.c_str()[i] is unnecessary. Use s[i], or better yet, use a for-range loop over the string:

for (auto c : myString) {...}

Upvotes: 4

Related Questions