I am getting an infinite loop with my method and I am unsure why. I am working on a method that is suppose to convert the bits from a decimal to a binary form. I can't see what is happening since I am getting an infinite loop when I run this method. I was hoping I could get some help why.
Here is my code:
int binToDec(char* bin)
{
int i = 0;
int result = 0; // (1) start the decimal result at 0.
while(bin != "\n");// (2) remove the most significant binary digit(leftmost) and add it to the result.
{
if(bin[i] == '1')
{
result = result * 2 + 1;
}
else if(bin[i] == '0')
{
result *= 2;
}
printf("%d\n", result);
i++;
} // (3) If all binary digits have been removed, you're done. Stop.
// (4) Otherwise, multiply the result by 2 and go back to step 2.
return result;
}
/**
* Create two functions that do binary to decimal conversion and back. Their signatures (aka prototypes)
* should look like:
* int binToDec(char* bin);
* char* decToBin(int dec);
*
* For both functions, remember that your string will not hold 0s and 1s, but the characters ‘0’ and ‘1’.
* Use the offset to determine the binary value.
*/
char* decToBin(int dec)
{
int i;
double z;
for(i = 0; i < dec; i++)
{
z = pow(2, i);
printf("The bit is %d \n", z);
}
char *c = (char*) malloc(dec * sizeof(z));
while(dec % 2 != 0) //As long as the quotient is not 0, continue to divide the newest quotient by 2.
{
c[i] += dec % 2 + '0';
dec = dec / 2; //Divide the value by 2 and record the remainder.
i++;
}
return c;
}
int main()
{
int num;
char *ptr;
ptr = (char*) malloc(num * sizeof(decToBin(11001)));
printf("Call to binToDec given 1001 result in: %d\n", binToDec("11001"));
printf("Call to decToBin given 9 results in : %s\n", decToBin(11001));
free(ptr);
return 0;
}
Let me know. The infinite loop takes place in the first method.
while(bin != "\n");has two problems. 1. You can't use!=to compare strings, you have to usestrcmp(). 2. The;at the end of the line is making this a loop with no body.==and!=to compare them.