I'm trying to make a binary calculator and I just can't find what's going wrong:
#include <stdio.h>
void dec2bin(long decimal, char *binary);
void dec2bin1(long decimal2, char *binary2);
int binaryAddition(int,int);
int main(void){
long int binarym1,binarym2,multiply=0;
int digit,factor=1;
long decimal;
long decimal2;
char binary[80];
char binary2[80];
printf("\n\n Please enter the first value : ");
scanf("%ld",&decimal);
dec2bin(decimal,binary);
printf("\n\n Now enter a second value : ");
scanf("%ld",&decimal2);
dec2bin1(decimal2,binary2);
printf("\n The binary value of %ld is %s \n",decimal,binary);
printf("\n The binary value of %ld is %s \n",decimal2,binary2);
binarym1 = (long int) binary;
binarym2 = (long int) binary2;
printf("\n The binary is %s \n",binarym1); //test - please ignore
while(binarym2!=0){
digit = binarym2 %10;
if(digit ==1){
binarym1=binarym1*factor;
multiply = binaryAddition(binarym1,multiply);
}
else
binarym1=binarym1*factor;
binarym2 = binarym2/10;
factor = 10;
}
printf("The answer is: %ld",multiply);
getchar(); // wait
getchar(); // wait
return 0;
}
int binaryAddition(int binarym1,int binarym2){
int i=0,remainder = 0,sum[20];
int binarySum=0;
while(binarym1!=0||binarym2!=0){
sum[i++] = (binarym1 %10 + binarym2 %10 + remainder ) % 2;
remainder = (binarym1 %10 + binarym2 %10 + remainder ) / 2;
binarym1 = binarym1/10;
binarym2 = binarym2/10;
}
if(remainder!=0)
sum[i++] = remainder;
--i;
while(i>=0)
binarySum = binarySum*10 + sum[i--];
return binarySum;
}
void dec2bin(long decimal, char *binary)
{
int k = 0, n = 0;
int neg_flag = 0;
char temp[80];
int remain;
// take care of negative input
if (decimal < 0)
{
decimal = -decimal;
neg_flag = 1;
}
do
{
remain = decimal % 2;
// whittle down the decimal number
decimal = decimal / 2;
// converts digit 0 or 1 to character '0' or '1'
temp[k++] = remain + '0';
} while (decimal > 0);
if (neg_flag)
temp[k++] = '-'; // add - sign
else
temp[k++] = ' '; // space
while (k >= 0)
binary[n++] = temp[--k];
binary[n-1] = 0;
}
void dec2bin1(long decimal2, char *binary2)
{
int k = 0, n = 0;
int neg_flag = 0;
char temp[80];
int remain1;
// take care of negative input
if (decimal2 < 0)
{
decimal2 = -decimal2;
neg_flag = 1;
}
do
{
remain1 = decimal2 % 2;
decimal2 = decimal2 / 2;
// converts digit 0 or 1 to character '0' or '1'
temp[k++] = remain1 + '0';
} while (decimal2 > 0);
if (neg_flag)
temp[k++] = '-'; // add - sign
else
temp[k++] = ' '; // space
while (k >= 0)
binary2[n++] = temp[--k];
binary2[n-1] = 0;
}
Output Example:
Please enter the first value: 45
Now enter a second value: 22
The binary value of 45 is 101101
The binary value of 22 is 10110
The answer is: 0
Funny thing is it produces NO error messages so I have no clue what's going on... help...