Convert a string of binary into an ASCII string (C++)

前端 未结 4 785
我在风中等你
我在风中等你 2021-02-05 23:19

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

4条回答
  •  一整个雨季
    2021-02-05 23:53

    #include 
    #include 
    #include 
    
    using namespace std;  
    
    int main()
    try
    {
    
       string myString = "Hello World"; // string object
    
       vector> 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';
    }
    

    output : Hello World

    Fastest way to Convert String to Binary?

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

    Convert a string of binary into an ASCII string (C++)

    To convert binary to string, I referred to the answer above link, the answer of Dale Wilson.

提交回复
热议问题