I am working on a program that reads in two decimal numbers from the command line, converts them to binary, adds them, then outputs the sum of the binary and decimal.
I made a function that converts the decimal input into binary, but now I can't figure out how to get those values into an int array.
For Example: Input: ./a.out 3 2
my function converts 3 into 11 and 2 into 10
now I need to put those values at the end of a int array so it looks like this: 0000000000000000000000000000011 and 0000000000000000000000000000010
That way my logic for adding the binary numbers can work properly.
Here is my attempt but it is saying it can assign int from void:
#include <iostream>
#include <cstdlib>
#include <string.h>
using namespace std;
void binary(int);
int main(int argc, char* argv[])
{
if(argc != 3)
{
cerr << "Invalid number of operands" << endl;
return 1;
}
int i;
int arg1 = atoi(argv[1]);
int arg2 = atoi(argv[2]);
int sum = arg1 + arg2;
int a[32];
int b[32];
int c[32];
int carry = 0;
bool print = false;
for(i = 0; i < 32; i++)
{
a[i] = 0;
b[i] = 0;
c[i] = 0;
}
for(i = 31; i >= 0; i--)
{
a[i] = binary(arg1); //PROBLEM AREA
b[i] = binary(arg2); //PROBLEM AREA
}
for(i = 31; i >= 0; i--)
{
if (a[i] == 1 && b[i] == 1 && carry == 0)
{
c[i] = 0;
carry = 1;
}
else if (a[i] == 1 && b[i] == 0 && carry == 0)
{
c[i] = 1;
carry = 0;
}
else if (a[i] == 0 && b[i] == 0 && carry == 0)
{
c[i] = 0;
carry = 0;
}
else if (a[i] == 0 && b[i] == 1 && carry == 0)
{
c[i] = 1;
carry = 0;
}
else if (a[i] == 1 && b[i] == 1 && carry == 1)
{
c[i] = 1;
carry = 1;
}
else if (a[i] == 1 && b[i] == 0 && carry == 1)
{
c[i] = 0;
carry = 1;
}
else if (a[i] == 0 && b[i] == 0 && carry == 1)
{
c[i] = 1;
carry = 0;
}
else if (a[i] == 0 && b[i] == 1 && carry == 1)
{
c[i] = 0;
carry = 1;
}
}
if(carry == '1')
cout << carry;
for (i = 0; i < 32; i++)
{
if (c[i] == 1)
print = true;
if (print)
cout << c[i];
}
cout << " = " << sum;
cout << endl;
return 0;
}
void binary(int number)
{
int remainder;
if(number <= 1)
{
cout << number;
return;
}
remainder = number % 2;
binary(number >> 1);
cout << remainder;
}
Any ideas or suggestions would be appreciated!
void binary(int);
returns avoid
so How can you assign avoid
to anint
?void
means you are actually returningnothing
. How can nothing(void
) be assigned to something(int
)? – Alok Save Sep 16 '11 at 5:33