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

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

    An alternative if you're using C++11:

    #include 
    #include 
    #include 
    #include 
    
    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 bitset is part of C++11.

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

提交回复
热议问题