Full c++ program that convert any string to binary format

 /*C++ program to convert

string into binary string*/
#include <bits/stdc++.h>
#include<iostream>
using namespace std;
// user Define function
void StringToBinaryNumber(string);
int main()
{

string UserInput;
cout<<"Enter your full name:";
  getline(cin,UserInput);// to read more than one words( including spaces)
StringToBinaryNumber(UserInput);
return 0;
}
void StringToBinaryNumber(string fname)
{
int lengthofstring,asciivalueOfstring ;
string binaryValue;

lengthofstring= fname.length();
for (int i = 0; i <= lengthofstring; i++)
{
  /*convert each char to ASCII value*/
  asciivalueOfstring = int(fname[i]);
  // Convert ASCII value to binary
   binaryValue = "";
  while (asciivalueOfstring > 0)
  {
   (asciivalueOfstring % 2)? binaryValue.push_back('1') :binaryValue.push_back('0');//  ternal operators (?:)
  asciivalueOfstring /= 2;
  }
  reverse(binaryValue.begin(), binaryValue.end());// function that reverse the binary digits.
  int check=binaryValue.length();// check the length of the bit to make eight
  if(check==1){
   cout<<0000000<<binaryValue<<" ";
  }
  else if(check==2){
  cout<<000000<<binaryValue<<" ";
  }
  else if(check==3){
    cout<<00000<<binaryValue<<" ";
  }
  else if(check==4){
  cout<<0000<<binaryValue<<" ";
  }
  else if(check==5){
  cout<<000<<binaryValue<<" ";
  }
 
  else if(check==6){
   cout<<00<<binaryValue<<" ";
  }
  else if(check==7){
  cout<<0<<binaryValue<<" ";
  }
  else{
  cout <<binaryValue << " ";
  }
 
}
}

Comments

Post a Comment

Popular posts from this blog

Solutions for even numbered questions in C++ exercises for beginners

C++ sample Exams with their answers