In this assignment, you are going to write a program for the following tasks. Yo
ID: 3876314 • Letter: I
Question
In this assignment, you are going to write a program for the following tasks. You must submit only a single cpp file.
Task 1: write a function that takes input a positive integer int n, and returns a string s. The function should store the binary representation of n starting from the most significant bit. (Most significant bit means the left most bit.) For example, if the input is 26, then the function returns the string s = “11010”. Here you do not need to worry about the problem of overflow.
Task 2: write a function that converts a binary number into a decimal number. In particular, the function takes input a string s that represents the binary digits from the most significant bit to the least significant bit. Your function returns an integer that is equal to the number s represents. For example, if your string is 11010, your return should be 26. You can assume that there is no overflow.
Note: if you don’t know the “string” type in c++, google it.
Task 3: In your main function, you should write some test cases to test your Tasks 1 and 2. The format is flexible.
Explanation / Answer
#include<iostream>
#include<string>
using namespace std;
//function to convert decimal to binary
void decToBinary(int n)
{
string str="";
int binaryno[1000];
int i = 0;
while (n > 0) {
binaryno[i] = n % 2;
n = n / 2;
i++;
}
for (int j = i - 1; j >= 0; j--)
str += to_string(binaryno[j]);
cout<< str<<endl;
}
//function to convert binary to decimal
int binaryToDecimal(string n)
{
string num = n;
int decno = 0;
int base = 1;
int len = num.length();
for (int i=len-1;i>=0;i--)
{
if (num[i] == '0')
{
decno += 0*base;
base = base * 2;
}
else
{
decno += 1*base;
base = base * 2;
}
}
return decno;
}
int main()
{
//testing functions using input
int n = 26;
decToBinary(n);
string num = "11010";
cout<<binaryToDecimal(num)<<endl;
return 0;
}