How to write a C Program to Converts a number to a string in C Programming Language ?
Solution:
- #include <string.h> /* strcat */
- #include <stdlib.h> /* strtol */
- int bit_count(int);
- // Converts a number to a string.
- char *tobin(int n)
- {
- int c, d, count;
- char *pointer;
- count = 0;
- pointer = (char*)malloc(bit_count(~0));
- if ( pointer == NULL )
- exit(EXIT_FAILURE);
- for ( c = 31 ; c >= 0 ; c-- )
- {
- d = n >> c;
- if ( d & 1 )
- *(pointer+count) = 1 + '0';
- else
- *(pointer+count) = 0 + '0';
- count++;
- }
- *(pointer+count) = '\0';
- return pointer;
- }// End *tobin