#include <string.h>
#include <stdio.h>
#include <iostream>
using namespace std;

char *ascii2binary(char *input,char *dst)
{       
   unsigned char bit;
   char *start = dst;

for (int i = 0; i < strlen(input); i++) {
   for ( bit = 1 << (8 - 1); bit; bit >>= 1 )
   {    
      *dst++ = input[i] & bit ? '1' : '0';
   }    
}
   *dst = '\0';
   return start;
}//ascii2binary

unsigned long binaryToDecimal(char *binary, int length)
    {
        int i;
        unsigned long decimal = 0;
        unsigned long weight = 1;
        binary += length - 1;
        weight = 1;
        for(i = 0; i < length; ++i, --binary)
        {
            if(*binary == '1')
                decimal += weight;
            weight *= 2;
        }
        return decimal;
    }
        
void binary2ascii(char *binary, char *outchar)
{
int binaryLength = strlen(binary);
int symbolCount = binaryLength / 8 + 1;
    int i;
    for(i = 0; i < binaryLength; i+=8, binary += 8)
    {
        char *byte = binary;
        byte[8] = '\0';
        *outchar++ = binaryToDecimal(byte, 8);
    }
    outchar -= symbolCount;
           
}//binary2ascii


int main () {


char a[]="DKMAHAnAOmzjgLdANONzKgOzKon@OInAMKnALIzLDzn@OzANOInAnazLDzAnmzjOOgIzn@OzHAICxzKINzNOnOgEAIKnALIzf@OIzKzHAICzAmzDoIMnALIAIFzjgLjLAInunLu?LAInzHAICmznOINznLzO`KMOgGKnOzEKIazjgLGHOEmzfAoggOInzDKEAHazLDzIOnfLgCzjgLnLMLHmyzOIdAgLIEOInmxzAmzOmjOMAKHHazNADDAMoHnzLdOgzMAgMoAnumfAnM@ONjLAInunLujLAInzHAICmzpmoM@zKmzNAKHuojzELNOEzmOgdOgmqyzz?@OmO?nzAmzAInOINONzn@Knz???zHAICmzGOzOKmaznLzMLIDAFogOyzz?azNOmAFIzz?@AmzmOHDuMLIDAFogKnALIzAmzAEjHOEOInONzn@gLoF@zKIzO`nOImAGHOLjnALIzIOFLnAKnALIzEOM@KIAmExzf@OgOAIzOKM@zOINzLDzn@OzHAICNOmMgAGOmznLzn@OzLn@OgzAnmzMKjKGAHAnAOmzKINzgOkoAgOEOInmy?Hn@LoF@zn@OzLjnALIzIOFLnAKnALIzEOM@KIAmEzNOmMgAGONzAIzn@AmNLMoEOInzAmzmjOMADAONzAIznOgEmzLDzn@Oz?AICz?LIngLHz?gLnLMLHzp???qxn@OzmKEOzDKMAHAnAOmzKgOzNOmAFIONznLzGOzomONzGazLn@OgzMLIngLHjKMCOnzzzz?@OzGKmAMzoIAnzLDzOIMKjmoHKnALIxzf@AM@zAmzjKmmONzKMgLmmzn@OzzzLgNOgznLzOmnKGHAm@zMLEEoIAMKnALImzLdOgzKzjLAInunLujLAInz@Oz???zHAICz????zDAgmnzmOINz???zjKMCOnmznLzMLIDAFogOzKIxz???z????zmOINz???zjKMCOnmznLzM@LLmOzKINzMLIDAaOgzjgLnLMLHmyzz?IMOzOKM@zLDzn@Oz";


cout << "original:\n" << a << "\nSIZE:" << strlen(a) << endl;

char *b = new char [ (strlen(a) * 8) + 1 ];
ascii2binary(a,b);
cout << "ascii2binary:\n" << b << "\nSIZE:" << strlen(b) << endl;

char *c = new char [ (strlen(b)/8) + 1 ];
binary2ascii(b,c);
cout << "binary2ascii:\n" << c << "\nSIZE:" << strlen(c) << endl;

delete [] b;
delete [] c;

}//main

compile on FreeBSD:

g++ filename.cpp

By: Mehdi Sadighian
Contact: mehdi.sadighian@hotmail.com
TAG: C, C++, binary to ASCII,ASCII to binary, char array,converter,convertion