Question

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

Was it helpful?

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;
}

OTHER TIPS

You can use:

std::string originalBack = ""; // result saved there
for (int i = 0; i < binaryString.size() / 16; i++) // take 16 bits each time
{
    std::string temp = binaryString.substr(i * 16, 16);
    std::bitset<16> temp2(temp);
    originalBack += temp2.to_ulong();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top