Re: convert int to string without using standard library (stdio.h)
- From: pete <pfiland@xxxxxxxxxxxxxx>
- Date: Mon, 17 Jul 2006 22:48:29 GMT
ceeques wrote:
Hi
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"
Results are not going to a standard output - I have a function to
readout/display string from memory.
/* BEGIN new.c */
#include <stdio.h>
void itoa(int n, char *s);
static char *sput_u(unsigned n, char *s);
static char *sput_up1(unsigned n, char *s);
int main(void)
{
char string[3] = "";
int i = 2;
char ch = 'A';
string[0] = ch;
itoa(i, string + 1);
puts(string);
return 0;
}
void itoa(int n, char *s)
{
if (0 > n) {
*s++ = '-';
*sput_up1(-(n + 1), s) = '\0';
} else {
*sput_u(n, s) = '\0';
}
}
static char *sput_u(unsigned n, char *s)
{
unsigned digit, tenth;
tenth = n / 10;
digit = n - 10 * tenth;
if (tenth != 0) {
s = sput_u(tenth, s);
}
*s = (char)(digit + '0');
return s + 1;
}
static char *sput_up1(unsigned n, char *s)
{
unsigned digit, tenth;
tenth = n / 10;
digit = n - 10 * tenth;
if (digit == 9) {
if (tenth != 0) {
s = sput_up1(tenth, s);
} else {
*s++ = '1';
}
*s = '0';
} else {
if (tenth != 0) {
s = sput_u(tenth, s);
}
*s = (char)(digit + '1');
}
return s + 1;
}
/* END new.c */
--
pete
.
- References:
- Prev by Date: Re: convert int to string without using standard library (stdio.h)
- Next by Date: Re: convert int to string without using standard library (stdio.h)
- 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
|