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

Consider the following dialog: Enter a binary number: 1110 Conversion to decimal

ID: 646013 • Letter: C

Question

Consider the following dialog:

Enter a binary number: 1110

Conversion to decimal: 14

Enter a binary number: 10010000

Conversion to decimal: 144

Enter a binary number: -1

All set !

Write the application implied above. In particular, the program will read a sequence of binary strings and convert each one to a decimal integer. The program will terminate when the string -1 is given. You must do the verbersion by hand, and NOT use the predefined functions in C++.

You must use a function for the conversion to binary, where the parameter to the function is the interger, and the reurn value is the equivalent binary string.

For the printout of this program, give two sample runs, one using the values from a sample dialog above, the other using values from some special case, e.g. an invalid input. You do not need to handle the special case.

Explanation / Answer

Program to convert binary strings to a decimal integer:

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;

int bin2dec(char* str) {
int n = 0;
int size = strlen(str) - 1;
int count = 0;
while ( *str != '' ) {
if ( *str == '1' )
n = n + pow(2, size - count );
count++;
str++;
}
return n;
}

int main() {
char* bin_str = "1100100";
cout << bin2dec(bin_str) << endl;
}

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