tags:

views:

72

answers:

2
+2  Q: 

string to binary

I convert a character to binary using std::bitset<CHAR_BIT> binary('c'); but this doesn't work for a string,

std::string str = "MyString";
std::bitset<SIZE_OF_STRING_IN_BITS> binary(str); //Error Exception

what should be the alternative?

+2  A: 

Why do you want to put the raw characters into a bitset? Why not a vector<char> ?

In any event you can get at the raw underlying bits of a string via the c_str() member function which usually returns a raw char* to the raw string data.

Robert S. Barnes
Because putting a char into a bitset allows you yo print out the bit pattern of character very easily (ie without writing code). Note: You seem to be confusing bits with char (c_str() returns a pointer to an array of char)
Martin York
@Martin York: Thanks for the explanation of why one would want to put the chars into a bitset. However, I'm not confusing bits with chars. `c_str` is the only way to get at the raw string data in order to put it into a `bitset`. The only reason I suggested a `vector<char>` was because I didn't understand what he's trying to do.
Robert S. Barnes
+1  A: 

You could repeat this action over every character of the string, shifting the bitset by CHAR_BIT to the left every time:

#include <bitset>
#include <string>
#include <iostream>
#include <numeric>
#include <climits>
template<size_t N>
std::bitset<N> string_to_bitset(const std::string& s)
{
    return accumulate(s.begin(), s.end(), std::bitset<N>(),
           [](const std::bitset<N>& l, char r)
           {
               return std::bitset<N>(r) | l<<CHAR_BIT;
           });
}
int main()
{
    std::string str = "MyString";
    const size_t SIZE_OF_STRING_IN_BITS = CHAR_BIT * 8;
    std::bitset<SIZE_OF_STRING_IN_BITS> binary = string_to_bitset<SIZE_OF_STRING_IN_BITS> (str);
    std::cout << binary << '\n';
}

Seeing as the size of the bitset has to be a constant expression, I would go with boost::dynamic_bitset unless this string is a compile-time constant.

Cubbi
Clever use of template parameters. But that only works with strings of fixed length known at compile time.If you rework this to use the boost::dynamic_bitset it can work with runtime calculated lengths.
Martin York