Re: convert int to string without using standard library (stdio.h)



ceeques wrote:
I am a novice in C. Could you guys help me solve this problem -

I need to convert integer(and /short) to string without using sprintf
(I dont have standard libray stdio.h).

for instance:-
int i =2;
char ch 'A'

My result should be a string ==> "A2"

See if this can help you:

#include <string.h>

char * itostrappend (char * str, int v, int base) {
char d[2];
int rem = v % base;
if (rem < 0) {
strcat (str, "-");
v = -(v / base);
rem = -rem;
} else v /= base;
d[0] = "0123456789abcdefghijklmnopqrstuvwxyz"[rem];
d[1] = '\0';
if (v) str = itostrappend (str, v, base);
strcat (str, d);
return str + strlen (str);
}

void itostr (char * str, int v, int base) { /* Simple wrapper */
str[0] = '\0';
itostrappend (str, v, base);
}

Its not very fast, but it works, and its performance is O(log(v))
(exercise to the reader.) Unfortunately it also requires O(log(v))
stack space.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

.



Relevant Pages