Integer to ASCII

Dr. Maykel Alonso January 18, 20132 comments Coded in C

This code converts a long integer to a char* pointer (string). The returned value could be in octal, in decimal or in hexadecimal.

/***** integerToAscii.h *****/

#define BASE_OCTAL			8
#define BASE_DECIMAL			10
#define BASE_HEXADECIMAL		16

#define BUFFER_SIZE			32

char* integerToASCII(long int value, int base);

/***** integerToAscii.c *****/

char* integerToASCII(long int value, int base){
	
	int aux;
	static char buf[BUFFER_SIZE] = {0};

        int isNeg=0;
        if (value == 0) {
                buf[0]='0';
                return &buf[0];
        }
        if (value<0) {
                isNeg = 1;
                value *= -1;
        }	

	for(aux=BUFFER_SIZE; value && aux ; --aux, value /= base){	
		buf[aux] = "0123456789abcdef"[value % base];
	}

	if (isNeg)  {
		buf[aux] = '-';
		return &buf[aux];
	}

	return &buf[aux+1];
}