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; }



LinkBack URL
About LinkBacks




I used to be an adventurer like you... then I took an arrow to the knee.