Program: Converting text to binary




Converts a string of text into a sequence of binary digits.

Code below:

// Converting text strings to binary - Phil Gardner

#include <iostream>

using namespace std;

// - - - - - - - - - - - - - - - - - - - - - -

string convertDenaryToBinary( int denaryValue )
{
    string result = "";
    int placeValue = 128;
    int remaining = denaryValue;

    for ( int index = 0;  index < 8;  index ++ )
    {
        if ( remaining / placeValue == 1 )
        {
            result.append( "1" );

            remaining = remaining - placeValue;
        }
        else
            result.append( "0" );

        placeValue = placeValue / 2;
    }

    return result;
}

// - - - - - - - - - - - - - - - - - - - - - - - -

int main()
{
    string myText;
    char singleChar;
    int len, asciiCode;

    cout << endl << "Type in your text: ";
    getline( cin, myText );

    // Check we have at least one character in the text
    len = myText.length();

    if ( len > 0 )
    {
        cout << endl << "Converting each character to 8-bit binary..." << endl << endl;

        string wholeMessage = "";
        string binaryCode;

        for ( int pos = 0;  pos < len;  pos++ )
        {
            singleChar = myText[ pos ];

            asciiCode = int( singleChar );

            binaryCode = convertDenaryToBinary( asciiCode );

            wholeMessage.append( binaryCode );

            cout << '\t' << singleChar << " " << binaryCode << endl;
        }

        cout << endl << "Entire text in binary is... " << endl << endl;
        cout << wholeMessage << endl;
    }
    else
    {
            cout << endl << "No text at all?" << endl;
            cout << "We're not going to store many bits are we?";
    }  // end of length decision

    cout << endl << endl;

}