Thursday, 5 January 2012

C++ Program to input any string upto 500 characters and convert the same into binary


C++ Program to input any string upto 500 characters  and convert the same into binary.

 #include <iostream.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>

char *entry, letter, choice[2];
int ascii, len, binary[8], total;
void prog();

int main()
{
      clrscr();
      prog();
      return 0;
}

void prog()
{
   entry = new char[501];
   cout<<"Enter string to convert (up to 500 chars): ";
   cin.getline(entry, 500);
   len = strlen(entry);  /* get the number of characters in entry. */
   for(int i = 0; i<len; i++)
   {
      total = 0;
      letter = entry[i]; /* store the first letter */
      ascii = letter;    /* put that letter into an int, so we can
                see its ASCII number */
      while(ascii>0) /* This while loop converts the ASCII # into binary,
            stores it backwards into the binary array. */
      {
     if((ascii%2)==0)
     {
        binary[total] = 0;
        ascii = ascii/2;
        total++; /* increasing by one each time will yeild the
            number of numbers in the array. */
     }
     else
     {
        binary[total] = 1;
        ascii = ascii/2;
        total++;
     }
      }
      total--;
      while(total>=0)
      {
     cout<<binary[total];
     total--;
      }
   }
   delete[] entry; /* free up the memory used by entry */
   cout<<endl<<"Do again(1 = yes, 2= no)?: ";
   cin.getline(choice,3);
   if(choice[0] == '1')
      prog();
   else
      exit(0); /* quits the program */
}

0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More