Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a Ct+ program to input a binary number and convert it to a decimal number.

ID: 3911880 • Letter: W

Question

Write a Ct+ program to input a binary number and convert it to a decimal number. Input the number in a character array, The Input can only be In the form of 1s and 8s In order to convert a binary number to a decimal number, you have to multiply the right most binary digit with 2 (i.e. 1), the next binary digit with 21, the next with 2 and so on and then compute the sum of these numbers. For example: For input 111, the answer is: 1x21x2+1x21x4 1x2 + 1x1 -7 For input 100, the answer is: 1x22+ 0x2+0x2 1x4 0x2 +0x1 4 Note: you are not required to create any functions for this question er a binary number, (Is and 0) 1111 he equivalent decimal number is:15 rocess returned (0x0) execution time :4.883 ress any key to cont Inue. Enter a binary number (ds and e Il The equivalent decimal number is:3 rocess returned &(0x0) execution time 1.513

Explanation / Answer

/*The program is written considering the input as character array. The exception(characters other than '0' & '1') is not handeled as not asked */

#include <iostream>

#include <chrono>
#include <string>
#include <cstring>
#include<math.h>

using namespace std;
using namespace std::chrono;

int main()
{
char c='f';
while(c){
  
string input="";
  
int decimal=0;
  
cout<<" Enter a binary number (1s and 0s): ";
cin>>input; //Character array is stored as string as input is of variable size
  
auto start = high_resolution_clock::now(); //measure the starting time
  
char binary[input.size()];
strcpy(binary, input.c_str()); //convert back the string to Character array
  
int s=sizeof(binary)-1;
  
//logic to convert binary to decimal
  
for (int i=0;i<sizeof(binary);i++){
decimal+=(binary[i]-'0')*(pow(2,s));
s--;
}
  
auto stop = high_resolution_clock::now();//measure the end time
  
auto duration = duration_cast<microseconds>(stop - start); //execution time microseconds
float dur=duration.count();
  
cout<<"The equivalent decimal number is:"<<decimal<<endl;
cout<<"process returned 0 (0x0) execution time : "<< dur/1000000<< " s" << endl;
cout<<"Press any key to continue.";
cin>>c;
  
//to continue the loop
if(c)
continue;
else
break;
}


return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote