Thread: Converting Decimal to Binary

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    38

    Converting Decimal to Binary

    Hello all,

    This is my project..
    "Write a function to return the binary representation of the number x as a character string. For example : if x = 17 is passed to the function the return value should be a pointer to the string
    00000000000000000000000000010001.
    Below please find the main function to test your code."

    So I have written the code and have gotten it to work but I cannot figure out how to get it to work so that "the return value should be a pointer to the string." as of now I have in commented out because it is printing out the binary number twice. But if I comment out the for loop and printf statement in the function and run it I dont get anything. Im still very new to C so any help would be appreciated. Thanks!

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    char *int_to_binary(int);
    char b[80];
    int main(void)
    {                                           // Call function int_to_binary to print a number in binary
        int x=0;
        char *ptr;
    
        if(setvbuf(stdout, NULL, _IONBF,0))
        {
            perror("failed to change the buffer of stdout");
            return EXIT_FAILURE; //clears buffer
        }
    
        printf("This program will convert the users input from decimal to binary.\n");
        printf("Enter a decimal number: ");
        scanf("%d",&x);
        ptr = int_to_binary(x);
        //printf("%s\n", int_to_binary(x));
        return 0;
    }
    
    char *int_to_binary(int x)
    {
        int i;
        for(i=31; i>=0; i--)
        {
            b[i]= x%2;
            x/=2;
        }
        b[33]='\0';
        for(i=0; i<=31;i++)
            printf("%d",b[i]); 
        return b;
    }

  2. #2
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    you are close. instead of writing the numeric value 1 or 0 to b, write the character '0' or '1' depending on the result of x%2.

  3. #3
    Registered User
    Join Date
    Feb 2012
    Posts
    2
    int_to_binary(x) returns the address of the first element of array b, the array's address is a long integer so you can't use it in printf with "%s".
    Try: printf("%s\n", *(int_to_binary(x))

  4. #4
    Registered User
    Join Date
    Sep 2011
    Posts
    38
    Quote Originally Posted by EuroDominus View Post
    int_to_binary(x) returns the address of the first element of array b, the array's address is a long integer so you can't use it in printf with "%s".
    Try: printf("%s\n", *(int_to_binary(x))
    I tried putting in that printf state but my output is still (null)
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    char *int_to_binary(int);
    char b[80];
    int main(void)
    {                                           // Call function int_to_binary to print a number in binary
        int x=0;
        char *ptr;
    
        if(setvbuf(stdout, NULL, _IONBF,0))
        {
            perror("failed to change the buffer of stdout");
            return EXIT_FAILURE; //clears buffer
        }
    
        printf("This program will convert the users input from decimal to binary.\n");
        printf("Enter a decimal number: ");
        scanf("%d",&x);
        ptr = int_to_binary(x);
        printf("%s\n", *(int_to_binary(x))); //when using any of these 2 printf statements and i run the prgram the output is (null) after inputting my decimal
        //printf("%s\n", int_to_binary(x));
        return 0;
    }
    
    char *int_to_binary(int x)
    {
        int i;
        for(i=31; i>=0; i--)
        {
            b[i]= x%2;
            x/=2;
        }
        b[33]='\0';
        //for(i=0; i<=31;i++)  //these are the two lines that I have added in order to get the correct output, but according to the project i shouldnt need them correct?
            //printf("%d",b[i]);
        return b;
    }

  5. #5
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    No! No globals! Why have the function return something if you're making it global?

    @euro:
    Code:
    printf("%s\n", *(int_to_binary(x))
    /* this will AT BEST give just a zero or a one, but probably will emit warnings and then segfault */
    Just get rid of the global, make the function truly return a char pointer (not a char array, don't compilers warn you about that?), and then printf with "%s" like any other string.

  6. #6
    Registered User
    Join Date
    Sep 2011
    Posts
    38
    right but thats what im asking help on. I know that thats not the correct printf statement. Also I know that the other printf statement in the function is not supposed to be there but thats what I cant figure out is how to "make the function truly return a char pointer". Also Im using eclipse and was not getting any errors but this is the first time ive used it and Im still figuring out how to build/clean/debug. Thanks!

  7. #7
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    Get rid of the global. You can "pass" it two ways, I'll prototype them

    Code:
    char *function() 
    {
        char *ret = malloc(10);
        /* stuff */
        return ret;
    }
    
    char *result = function();
    /* use it */
    free(result);
    or

    Code:
    void function(char **input)
    {
        char *parse = *input;
        /* modify parse however you want */
        return; /* not really necessary to return */
    }
    
    char *result = malloc(10);
    function(&result);
    /* use it */
    free(result);

  8. #8
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    You could also do:

    Code:
    char *int_to_binary(int x, char *b) // <-- adding char* argument
    {
        int i;
        for(i=31; i>=0; i--)
        {
            b[i]= x%2;
            x/=2;
        }
        b[33]='\0';
    
        return b;
    }
    Keep in mind that b, has to be an array which can keep the entire string. You could typedef it but, that would hide the size.

  9. #9
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by EuroDominus View Post
    int_to_binary(x) returns the address of the first element of array b, the array's address is a long integer so you can't use it in printf with "%s".
    By array's address, I assume you mean the address of the first element, which is a char *. The address of the array would be &b, which is of type char (*)[80]. Either way, however, the address is not "a long integer". Pointers are not interchangeable with ints or longs. They are different types. The addresses stored in pointers are integral, i.e. they are numbers that can't have a decimal portion, but they are different from ints or longs.
    Try: printf("%s\n", *(int_to_binary(x))
    If int_to_binary returned a long integer, as you claimed, *(int_to_binary(x)) would be dereferencing a long, which you can't do. You can only dereference a pointer. As it happens, it returns a char * (which is correct per the problem specification), but the leading * would still be incorrect. That would dereference the char * into just a single char. For that you would need %c, but then you would only print one "bit" from your array.

    The problem, as memcpy pointed out, is that the OP is not filling the char array with printable chars (ASCII '0' and '1'). The fix is to replace the guts of the loop in int_to_binary with the following:
    Code:
    for (i = 31; i >= 0; i--)
    {
        b[i] = (x%2) + '0';  // add ASCII '0' to the result, so you get a printable '0' or '1'
        x /= 2;
    }
    Note, for returning an array, you could also make it static inside the function:
    Code:
    char *int_to_binary(int x)
    {
        static char b[33];
    ...
        return b;
    }
    This wont work for threaded applications or if called recursively (directly or indirectly), but that's not an issue here. Or declare the array in main and pass it in to be filled:
    Code:
    char *int_to_binary(int x, char *b)
    {
        return b;
    }
    ...
    // in main
    char b[33];
    printf("%s\n", int_to_binary(x, b));
    It's good practice to pass in the length of b as well, to avoid your function causing a buffer overflow, but again, that's not a big issue here.

  10. #10
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Quote Originally Posted by anduril462 View Post
    The problem, as memcpy pointed out, is that the OP is not filling the char array with printable chars (ASCII '0' and '1'). The fix is to replace the guts of the loop in int_to_binary with the following:
    I just copied the OPs original code to show how he could easily add a char* to his arguments. In response to his last question of how to "make the function truly return a char pointer".


    Quote Originally Posted by anduril462 View Post
    Note, for returning an array, you could also make it static inside the function:
    Code:
    char *int_to_binary(int x)
    {
        static char b[33];
    ...
        return b;
    }
    This wont work for threaded applications or if called recursively (directly or indirectly), but that's not an issue here.
    It could be an issue if it's called several times to different variables as they all would point to the same string.
    Last edited by Subsonics; 02-08-2012 at 06:33 PM.

  11. #11
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by Subsonics View Post
    I just copied the OPs original code to show how he could easily add a char* to his arguments. In response to his last question of how to "make the function truly return a char pointer".
    Oh, that wasn't directed at you, it was for EuroDominus and the OP. I never saw your post until now as I was busy writing mine at the time.

    It could be an issue if it's called several times to different variables as they all would point to the same string.
    Ahh, yes. I always for get about that one.

  12. #12
    Registered User
    Join Date
    Sep 2011
    Posts
    38
    Quote Originally Posted by anduril462 View Post

    The problem, as memcpy pointed out, is that the OP is not filling the char array with printable chars (ASCII '0' and '1'). The fix is to replace the guts of the loop in int_to_binary with the following:
    Code:
    for (i = 31; i >= 0; i--)
    {
        b[i] = (x%2) + '0';  // add ASCII '0' to the result, so you get a printable '0' or '1'
        x /= 2;
    }
    Thanks so much everyone!! The following code worked perfectly! I was trying to use the static char as mentioned earlier today because I was thinking that was an issue as well but it still would not run because i was not getting a printable 0 or 1. Also I apologize for not being more specific but the assignment calls for us to use the exact functions..
    Code:
    char *int_to_binary(int x)
    {
    }
    int main(void) {
    // Call function int_to_binary to print a number in binary
    printf("%s\n", int_to_binary(17));
    return EXIT_SUCCESS;
    }
    Anyways thanks again guys!! Im still a noob but slowly getting there! lol

  13. #13
    Registered User
    Join Date
    Jan 2012
    Posts
    69
    simpy return &b instead of b, than you return a pointer value.

  14. #14
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    Quote Originally Posted by kevinstrijbos View Post
    simpy return &b instead of b, than you return a pointer value.
    If b is a local variable to the function, then returning &b creates a dangling pointer since b will be destroyed.

  15. #15
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. converting decimal to binary in stack
    By Cpe Engeya in forum C++ Programming
    Replies: 4
    Last Post: 05-08-2009, 07:24 PM
  2. Converting binary string to decimal
    By Sharke in forum C Programming
    Replies: 3
    Last Post: 03-30-2009, 12:18 AM
  3. Converting decimal to binary within a I/O program
    By RandomX in forum C Programming
    Replies: 4
    Last Post: 11-26-2006, 09:25 AM
  4. Converting decimal to binary
    By ubernos in forum C Programming
    Replies: 3
    Last Post: 12-06-2005, 10:09 AM
  5. Converting decimal to binary?
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 04-17-2002, 08:21 AM