Convert a string of binary code to an ASCII string (C ++)

I have a string variable containing 32 bits of binary code. What would be the best way to convert these 4 characters (8 bits - one character) represented by binary code back into their ASCII characters?

For example, the variable contains "01110100011001010111001101110100", which should be converted back to the string "test".

+4
source share
3 answers

Alternative if you are using C ++ 11:

#include <iostream>
#include <string>
#include <sstream>
#include <bitset>

int main()
{
    std::string data = "01110100011001010111001101110100";
    std::stringstream sstream(data);
    std::string output;
    while(sstream.good())
    {
        std::bitset<8> bits;
        sstream >> bits;
        char c = char(bits.to_ulong());
        output += c;
    }

    std::cout << output;

   return 0;
}

Note that the bitset is part of C ++ 11.

Also note that if the data is not generated correctly, the result will be truncated when sstream.good () returns false.

+6
source

, , , 8 "" , .

// error checking is for production code
// this means that you will have to ensure that:
// input is a string of inputlen chars where inputlen is a multiple of 8
// each char is either '0' or '1'
::std::string result;
for(size_t i = 0; i < inputlen; i += 8)
{
    for(size_t j = 0; j < 8; ++j)
        c = (c << 1) | "01"[input[i + j] - '0'];
    result.push_back(c);
}
0
#include <iostream>
#include <vector>
#include <bitset>

using namespace std;  

int main()
try
{

   string myString = "Hello World"; // string object

   vector<bitset<8>> us;           // string to binary array of each characater

   for (int i = 0; i < myString.size(); ++i)
   {
        // After convert string to binary, push back of the array
        us.push_back(bitset<8>(myString[i]));
   }

   string c;  // binary to string object

   for (int i = 0; i < us.size(); ++i)
    {
        // the function 'to_ulong' returns
        // integer value with the same bit representation as the bitset object.
        c += char(us[i].to_ulong());
    }

    cout << c;

}
catch (exception& e)
{
    cerr << "the error is : " << e.what() << '\n';
}

: Hello World

Fastest way to convert strings to binary?

To convert a string to binary, I referred to the link above.

Convert binary code string to ASCII string (C ++)

To convert binary to string, I mentioned the answer above the link, Dale Wilson's answer.

0
source

Source: https://habr.com/ru/post/1538428/


All Articles