Re: convert int to string without using standard library (stdio.h)
- From: websnarf@xxxxxxxxx
- Date: 17 Jul 2006 18:35:53 -0700
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/
.
- Follow-Ups:
- References:
- Prev by Date: read this
- Next by Date: Re: converting string into integer
- Previous by thread: Re: convert int to string without using standard library (stdio.h)
- Next by thread: Re: convert int to string without using standard library (stdio.h)
- Index(es):
Relevant Pages
|