C++ Assignment : Create a program which can maintain binary numbers, being able
ID: 3670306 • Letter: C
Question
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. To keep the assignment from getting too complicated, you’ll never need more than SIX binary digits, so consider that the upper limit of how many variables you’ll need in each binary class. 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 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.
Explanation / Answer
#include <iostream>
using namespace std;
// Converts decimal to binary
int convert_decimal_to_binary(int n){
int rem;
int i=1, sum = 0;
do{
rem = n%2;
sum = sum + (i*rem);
n = n/2;
i = i * 10;
}while(n>0);
cout << "Binary : " << sum <<endl;
return 0;
}
// returns binary represention number from binary array
int showBinary(int array[], int n){
int i,num=0;
for(i = 0; i <n; i++){
num = array[i] + num*10;
// printf("%d ", array[i]);
}
// printf(" num : %d ",num);
return num;
}
// adds to binary numbers and shows them
int addBinary(int a1[], int a2[]){
int i, c = 0;
int result[] = {0,0,0,0,0,0,0,0};
for(i = 7; i >=0 ; i--){
result[i] = ((a1[i] ^ a2[i]) ^ c); //a xor b xor c sum of bits as per binary theory bits
c = ((a1[i] & a2[i]) | (a1[i] &c)) | (a2[i] & c); //ab+bc+ca is the carry
}
result[i] = c;
return showBinary(result,8);
}
// converts binary to decimal representation
int convert_binary_to_decimal(int n){
int rem, base=1,res=0;
while(n>0){
rem = n % 10;
res = res + rem * base;
base=base*2;
n=n/10;
}
cout << "Decimal format : "<<res <<endl;
return 0;
}
int main()
{
// decimal to binary 34
int n = 34;
convert_decimal_to_binary(n);
// decimal to binary 32
n = 22;
convert_decimal_to_binary(n);
// binary to decimal 1001
n = 1001; // number in binary format
convert_binary_to_decimal(n);
// binary to decimal 111011
n = 111011; // number in binary format
convert_binary_to_decimal(n);
// addition of binary numbers 11 and 1110
int a[] = {0,0,0,0,0,0,1,1};
int b[] = {0,0,0,0,1,1,1,0};
cout << "binary addition : "<< addBinary(a,b) << endl;
// addition of binary numbers 1010 and 111
int c[] = {0,0,0,0,1,0,1,0};
int d[] = {0,0,0,0,0,1,1,1};
int addedBinary = addBinary(c,d);
convert_binary_to_decimal(addedBinary);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.