Convert a string of binary into an ASCII string (C++)
An alternative if you're 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 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.
#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';
}
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.
Try using this with method. Example:
#include <iostream>
#include <bitset>
#include <sstream>
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!