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



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
.



Relevant Pages

  • Re: socket communication: send & receive doesnt work right
    ... So I don't want to send a string as bytes. ... public void send_doubles(double vals, int len) throws ... // send a short acknowledgement to the server ... char *result; ...
    (microsoft.public.win32.programmer.networks)
  • Re: [PATCH] markers: modpost
    ... pointers to the name/format string pairs. ... The same can then be done with modules using the __markers section. ... +static void read_markers(const char *fname) ... int main ...
    (Linux-Kernel)
  • Re: [PATCH] markers: modpost
    ... This adds some new magic in the MODPOST phase for CONFIG_MARKERS. ... will be a neighbor of its format string. ... +static void read_markers(const char *fname) ... int main ...
    (Linux-Kernel)
  • Re: Is this code totaly a shit?
    ... | void UppStrg(char *Low, char *Upp, int cnt); ... whitespace-delimited string. ... You're also assuming that the representations of the characters ...
    (comp.lang.c)
  • Re: A string collection abstract data type
    ... duplicate string in Insert, InsertAt, ReplaceAt; ... used int instead of size_t for count and size for consistency with API. ... char *(StringCollection *SC, int idx, ... static int IsReadOnly; ...
    (comp.lang.c)