Hi all.
I am very new to programming and have been working on a program that can receive decimals or binary numbers and convert them. The decimal --> binary works fine. For some reason I cannot figure out I cannot get the "BinaryToDecimal" function to perform. By putting a "printf" into the for-loop I found that it only goes through one iteration and even then doesn't produce even a partially correct answer. Please advise!
Thanks a bunch.
P.S - since I am new please don't give elaborate or advanced ideas - I am in a course so they won't want us to use to many things we haven't learned yet..
Code:
#include <stdio.h>#include <string.h>
#include <math.h>
char* ReverseString (char _result[])
{
int start, end, length = strlen(_result);
char swap;
for (start = 0, end = length-1; start < end; start++, end--)
{
swap = *(_result + end);
*(_result + end) = *(_result + start);
*(_result + start) = swap;
}
return _result;
}
int IntegerToBinary (int _num, char* _str)
{
int i;
int devided = _num;
for (i = 0; devided > 0 ; i++)
{
*(_str + i) = devided % 2 + '0';
printf("%c %d\n", _str[i],i);
devided /=2;
}
*(_str + i) = '\0';
ReverseString(_str);
return 1;
}
int BinaryToDecimal (char _binary[])
{
int i;
int newnum = 0;
int length = strlen(_binary);
ReverseString(_binary);
for (i = 0; i < length; i++);
{
newnum += (*(_binary + i) + '0') * (pow(2, i));
printf("newnum - %d , length - %d",newnum, length);
}
return newnum;
}
int main()
{
char c;
int num;
char str[1000];
puts("a) Integer to binary (b) Binary to Integer");
c= getchar();
switch (c)
{
case 'a':
{
puts("Please type a decimal integer to change to binary");
scanf("%d", &num);
IntegerToBinary(num, str);
printf("Your number represented in binary is: %s\n", str);
break;
}
case 'b':
{
puts("Please type a binary number to change to integer");
scanf("%s", str);
num = BinaryToDecimal(str);
printf("Your binary number represented in decimals is: %d\n", num);
break;
}
default :
{
puts("Try again. a or b");
break;
}
}
return 0;
}