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
#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.