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

前端 未结 4 790
我在风中等你
我在风中等你 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:35

    Try using this with method. Example:

    #include 
    #include 
    #include 
    using namespace std;
    
    string BinaryStringToText(string binaryString) {
        string text = "";
        stringstream sstream(binaryString);
        while (sstream.good())
        {
            bitset<8> bits;
            sstream >> bits;
            text += char(bits.to_ulong());
        }
        return text;
    }
    
    int main()
    {
        string binaryString = "0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100";
        cout << "Binary string: " << binaryString << "!\n";
        cout << "Result binary string to text: " << BinaryStringToText(binaryString) << "!\n";
    
        return 0;
    }
    

    result code:

    Binary string: 0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100!                                                                                                  
    Result binary string to text: Hello World! 
    

提交回复
热议问题