Friday, April 8, 2011

#C_CODE: Integer to Ascii conversion

#include <stdio.h>
#include <string.h>
void reverse(char *s)
{
 int len = strlen(s) - 1;
 int i;
 for(i=0;i < strlen(s)/2; i++)
 {
  s[i]   ^= s[len];
  s[len] ^= s[i];
  s[i]   ^= s[len--];
 }
}

char *intoa(int num)
{
 static char buff[10];
 char *s = &buff[0];
 int sign;

 if((sign = num) < 0)
 {
  num = -num; //Make num positive  
 }

 do
 {
  *(s++) = (num%10) + '0';
 }while(num /= 10);
 
 if(sign < 0)
  *(s++) = '-';

 *(s) = '\0';
 reverse(&buff[0]);
 return (&buff[0]);
}

int main()
{
 int num,i;
 char *s;

 printf("Enter the num: ");
 scanf("%d",&num);
 s = intoa(num);
 printf("\nThe num %d in ascii is: ",num);
 for(i=0; i < strlen(s); i++)
  printf("\n%c",s[i]);

 fflush(stdin);
 getchar();
}

REF: C Programming Language-K&R

No comments: