HELP!!!! CODE HAS TO BE IN C++ Assignment : Create a program which can maintain
ID: 669049 • Letter: H
Question
HELP!!!! CODE HAS TO BE IN C++
Assignment: Create a program which can maintain binary numbers, being able to add them, as well as being able to convert them from binary to decimal, and decimal to binary. There are a number of ways to do this, from creating your own binary class to using an array of chars to being tricky with normal integers. To keep the assignment from getting too complicated, you’ll never need more than SIX binary digits, even in your addition results, so keep that in mind. Your code will need to perform the following feats:
Convert 34 to Binary
Convert 22 to Binary
Convert 1001 to Decimal
Convert 111011 to Decimal
Add 11 and 1110 in Binary, Return the Answer in Binary
Add 1010 and 111 in Binary, then Convert the Answer to Decimal
A general reminder, double-check your code’s output to make sure it’s correctly converting. And although many compilers offer built-in Binary-to-Decimal/Decimal-to-Binary converters, PLEASE DO NOT USE THESE BUILT IN CONVERTERS, as I will intentionally remove points for doing so. (40pts code, 10 pts per problem)
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
int convert_into_bin(int n){
int i = 1,binary = 0;
while (n > 0){
binary += i*(n % 2);
n /= 2;
i *= 10;
}
return binary;
}
int convert_into_dec(int n){
int i = 0,num = 0;
while (n > 0){
num += (n % 10)*pow(2,i);
n /= 10;
i++;
}
return num;
}
int add_and_return_in_bin(int a,int b){
int res_1 = convert_into_dec(a);
int res_2 = convert_into_dec(b);
return convert_into_bin(res_1 + res_2);
}
int add_and_return_in_dec(int a,int b){
int res_1 = convert_into_dec(a);
int res_2 = convert_into_dec(b);
return res_1 + res_2;
}
int main(){
cout << convert_into_bin(10) << endl;
cout << convert_into_dec(1010) << endl;
cout << add(1010,1110) << endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.