# Thread: Converting Decimal to Binary

1. ## 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.

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. 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. 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. Originally Posted by EuroDominus
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. 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. 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. 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. 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. Originally Posted by EuroDominus
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. Originally Posted by anduril462
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".

Originally Posted by anduril462
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.

11. Originally Posted by Subsonics
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. Originally Posted by anduril462

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. simpy return &b instead of b, than you return a pointer value.

14. Originally Posted by kevinstrijbos
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.