Convert a string of binary into an ASCII string (C++) -
I have a string variable in which 32 bit is binary. What will be the best way to convert these 4 characters (8 bits is one letter) that will return binary to their ASCII characters?
For example, a variable "01110100011001010111001101110100" should be transformed back to the string "test".
If you are using C ++ 11, then an alternative:
#include & lt; Iostream & gt; #include & lt; String & gt; # Include & lt; Sstream & gt; # Include & lt; Bitset & gt; Int main () {std :: string data = "01110100011001010111001101110100"; Std :: stringstream sstream (data); Std :: string output; While (sstream.good ()) {std :: bitset & lt; 8 & gt; Bits; Sstream & gt; & Gt; Bits; Four c = four (bits.To_Long ()); Output + = C; } Std :: cout & lt; & Lt; Output; Return 0; }
Note that binsets are part of C ++ 11.
Also keep in mind that if the data is not well formed, the result will be silently reduced when sstream.good () incorrectly returns.
Comments
Post a Comment