Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

ascii

binary

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 their ASCII characters?

For example, a variable contains "01110100011001010111001101110100" which should be converted back into the string "test".

like image 296
Craig Avatar asked Apr 28 '14 14:04

Craig


People also ask

How do you convert binary to string?

The naive approach is to convert the given binary data in decimal by taking the sum of binary digits (dn) times their power of 2*(2^n). The binary data is divided into sets of 7 bits because this set of binary as input, returns the corresponding decimal value which is ASCII code of the character of a string.

How do I convert to ASCII?

You must first convert the character to its ASCII value. In LiveCode, this is done with the charToNum function. Converting a number to the corresponding character is done with the numToChar function. The first of these statements converts a number to a character; the second converts a character to its ASCII value.


2 Answers

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! 
like image 119
Mirolim Majidov Avatar answered Sep 20 '22 11:09

Mirolim Majidov


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.

like image 24
Dale Wilson Avatar answered Sep 20 '22 11:09

Dale Wilson