( C++ ) a. Write a function that returns a decimal number from a binary string.
ID: 3858826 • Letter: #
Question
( C++ )
a. Write a function that returns a decimal number from a binary string. The function header is as follows: int bin2Dec(const string& binaryString) For example, binaryString 10001 is 17 (1x24 + 0x23 + 0x22 + 0x21 +1x20 =17). So, bin2Dec("10001") returns 17.
b. Write a function that parses a decimal number into a binary number as a string. The function header is as follows: string dec2Bin(int value) For example, dec2Bin (17) returns string “10001”.
c. Write a test program that prompts the user to enter a binary or decimal number and display its equivalent value in decimal or binary. (20 marks)
Explanation / Answer
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int bin2Dec(const string& binaryString) {
int sum = 0;
for(int i=binaryString.length()-1,j=0;i>=0; i--,j++){
int num = binaryString[i] - '0';
if(num == 1){
sum = sum + pow(2,j);
}
}
return sum;
}
string dec2Bin(int value) {
string s ="";
while(value > 0){
s = s + to_string(value %2);
value=value/2;
}
return s;
}
int main()
{
string binaryString;
cout << "Enter the binary string: ";
cin >> binaryString;
int decimalNum = bin2Dec(binaryString);
cout<<"Decimal number is "<<decimalNum<<endl;
cout<<"Binary string is "<<dec2Bin(decimalNum)<<endl;
return 0;
}
Output:
sh-4.2$ g++ -std=c++11 -o main *.cpp
sh-4.2$ main
Enter the binary string: 10001
Decimal number is 17
Binary string is 10001
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.