0

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.

6
  • I apologize, this is the wrong method. Let me post the correct one Commented Oct 14, 2019 at 16:37
  • while(bin != "\n"); has two problems. 1. You can't use != to compare strings, you have to use strcmp(). 2. The ; at the end of the line is making this a loop with no body. Commented Oct 14, 2019 at 16:40
  • One of the first things you should have learned about strings is that you don't use == and != to compare them. Commented Oct 14, 2019 at 16:41
  • @Barmar I apologize, I am new to C. Commented Oct 14, 2019 at 16:42
  • @Barmar and yikes I just found that I had the ; at the end. Commented Oct 14, 2019 at 16:44

2 Answers 2

1

Look at this line:

while(bin != "\n");

Even if the ; wasn't there the condition would never become true, just because you can't compare strings like that. It had to be

while( strcmp(bin, "\n") != 0 )

But looking at what should obviously have been the loop body you don't increment the pointer bin but an integer i. So finally, your condition should be

while( strcmp(bin+i, "\n") != 0)

or simply

while( bin[i] != '\n' )

... and without the `;' of course

And as @barmar mentioned correctly, if you call binToDec() with a string that contains no newline at all, you still have an infinite loop. So because bin should consist of '0' and '1' only, I would suggest:

  while( bin[i] == '0' || bin[i] == '1' ) 

or, if you want to support 'formatted' binary strings (e.g. with a space after every 8 digits)

  while( bin[i] != '\0' && bin[i] != '\n' ) 

your loop body would already be fine for that as you don't do anything if bin[i] is neither '0' nor '1'

Sign up to request clarification or add additional context in comments.

2 Comments

But his input strings don't end with newline, so the condition will never become true.
@barmar thanks, I must admit I didn't look at that. I will edit.
0

This loop

while(bin != "\n");
                 ^^^ 

is indeed an infinite loop because the string literal "\n" in most cases has a different address than a string literal pointed to by the pointer bin. Moreover even if to write

while( "\n" != "\n");

then the loop can be also infinite because the compiler (depending on its options) can store identical string literals as different objects.

This statement

ptr = (char*) malloc(num * sizeof(decToBin(11001)));

does not make sense because the pointer ptr is not used and the variable num was not initialized.

And this declaration

char *c = (char*) malloc(dec * sizeof(z));

does not make sense. For example why sizeof( double ) (the type of the variable z is double) is used? And the returned string from the function is not zero terminated.

Also in these calls

printf("Call to binToDec given 1001 result in: %d\n", binToDec("11001"));
                               ^^^^                             ^^^^^

printf("Call to decToBin given 9 results in : %s\n", decToBin(11001));
                              ^^^                             ^^^^^

there are typos.

It seems you mean the following

#include <stdio.h>

unsigned int binToDec( const char *bin )
{       
        unsigned int result = 0; // (1) start the decimal result at 0.   

        for ( ; *bin != '\0'; ++bin ) // (2) remove the most significant binary digit(leftmost) and add it to the result.
        {
            result = 2 * result + ( *bin == '1' );
        }       // (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;
}

int main(void) 
{
    const char *bin = "11001";

    printf( "Call to binToDec given %s result in: %u\n", bin, binToDec( bin ) );

    return 0;
}

The program output is

Call to binToDec given 11001 result in: 25

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.