Search code examples
c++stringbinarybitset

std::string to std::bitset represented by std::string and vice-versa


Now-now this can be a little confusing but I can't come up with a more simple title that could tell exactly what I mean. I have a string that I wish to convert to binary (each char to 16bit width binary) STRING. And then the binary string back to the original string. I have no problems converting the string to its binary "string".

std::string original = "The lazy fox jumped upon the fancy fence.";
std::stringstream bStream;
for (int i = 0, iMAX = original.size(); i < iMAX; ++i) {
    bStream << std::bitset<16>(original[i]);
}
std::string binaryString = bStream.str();

How could I convert this binaryString back to original?

Cheers, Joey


Solution

  • You can use something like

    std::string bin2str(std::string t_)
    {
        std::stringstream bStream(t_);
        std::string ret;
        std::bitset<16> t;
        while(bStream >> t) {
            ret += static_cast<char>(t.to_ulong());
        }
        return ret;
    }