简体   繁体   中英

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 get no 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.

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 aa 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) {...}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM