C Program to Converts a Number to a String.

How to write a C Program to Converts a number to a string in C Programming Language ?


Solution:
  1. #include <string.h>     /* strcat */
  2. #include <stdlib.h>     /* strtol */
  3. int bit_count(int);
  4. // Converts a number to a string.
  5. char *tobin(int n)
  6. {
  7.    int c, d, count;
  8.    char *pointer;
  9.    count = 0;
  10.    pointer = (char*)malloc(bit_count(~0));
  11.    if ( pointer == NULL )
  12.       exit(EXIT_FAILURE);
  13.    for ( c = 31 ; c >= 0 ; c-- )
  14.    {
  15.       d = n >> c;
  16.       if ( d & 1 )
  17.          *(pointer+count) = 1 + '0';
  18.       else
  19.          *(pointer+count) = 0 + '0';
  20.       count++;
  21.    }
  22.    *(pointer+count) = '\0';
  23.    return  pointer;
  24. }// End *tobin


Learn More :