Encoders
Hub for Computer Whizzes Register to join us

Encoders > More... > C > Program

/* Function itob(n,s,b) to convert the integer n into a base b character
   representation in the string s. */

#include <stdio.h>

void itob(int number, char string[], int n);

main()
{
	char a[100];
	itob(35,a,36);
        printf("%s\n",a);
}

void itob(int n, char s[], int b)
{
        void shift(char s[],int i);
        char a[]="Error";
	int i=0, sign;
        if(b>36)
	{
		while((s[i]=a[i])!='\0')
			i++;
		return;
	}
        if((sign=n)<0)
		n = -n;
	s[0]='\0';
	do
                shift(s,i), s[0]=n%b<10 ? '0'+n%b : 'A'+n%b-10, n/=b, i++;
        while(n>0);
        if(sign<0)
		shift(s,i), s[0]='-';
}

void shift(char s[],int i)
{
	int j;
        for(j=i; j>=0 ; j--)
		s[j+1]=s[j];
}