So I'm taking a new class that delves into assembly, but our professor is testing our C knowledge beforehand. This what he asks of us:
Return the binary representation of a 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.
Now, main and the function name are exactly what he has provided. So I need to basically write the function and return the string. What I was trying to do was call the function and use the value suggested (17), do the modulus to find the remainders, store that info, and then finally swap the stored values in the string so it will print in the right order (msb to lsb). My C programming class lightly covered strings and pointers so I am not great in that area, but I'm giving it my best shot. Any help or suggestions is appreciated. Thanks!
Code:#include <stdio.h> #include <stdlib.h> #include <math.h> char *int_to_binary(int x); int main(void) { int x = 17; printf("%s\n", int_to_binary(x)); return 0; } char *int_to_binary(int x) { int i, j, temp; char bin[32]; for(i=0; i<=31; i++) { bin[i]=x%2; x=x/2; } printf("%s\n", bin); for(j=0;j<=16; j++) { temp = bin[0+j]; bin[0+j] = bin[31-j]; bin[31-j] = temp; } return bin; }