A89: Re: tigcc - some REAL routines this time (updated)


[Prev][Next][Index][Thread]

A89: Re: tigcc - some REAL routines this time (updated)




Johan pointed out some minor errors in these to me, so here's a repost with
my typos and syntax and logic errors fixed and a few extra comments for
clarification.  If the TI-XGCC (an improved version of TI-GCC) zip would
work I would test these on my new PC here. . .

// -------------------------------------------------------------------------
// Int to String routines
// by Scott Noveck (scott@acz.org)
//
// These are strictly C99 code, NOT C85 or C90.  C99 is a new version of the
//   ANSI C standard passed last year.  This code uses C++ style "//"
//   comments, which will not be accepted by a strict ANSI C85 or C90
//   compiler.  TI-GCC is, to the extent of my knowledge, C99 compliant.
//
// These do NOT yet handle negative numbers and are NOT portable
//   although that can be fixed easily if necessary.
//
// Two versions follow below:
// inttostring gives only used digits or a single zero if the input is zero.
// inttostring_fixed gives a fixed number of digits.
// -------------------------------------------------------------------------

#define STORAGE_SIZE 5          // largest int (65545) is five digits long
                                // not including the terminating NUL byte

// function prototypes
char *inttostring(int num, char storage[]);
char *inttostring_fixed(int num, int digits, char storage[]);

char storage[STORAGE_SIZE+1]    // Leaving this global since there's no main
                                // here, but you would pass it to the
                                // functions below

// inttostring
// Input:  number to convert, char array to store string it
// Output: returns a pointer to the string _without_ leading zeros
//         if num is zero will return string "0"
char *inttostring(int num, char storage[])
{
    storage += STORAGE_SIZE+1;
    *(--storage) = '\0';
    do {
        *(--storage) = num % 10 + '0';
    } while (num/=10);
    return(storage);
}

// inttostring_fixed
// Input:  num to convert, number of digits, char array to store string to
// Output: returns a pointer to the string with specified number of digits
//           if necessary, only the least significant digits or leading
zeros
//           will be displayed.
char *inttostring_fixed(int num, int digits, char storage[])
{
    char *storagetmp;
    storagetmp = storage+STORAGE_SIZE+1;
    *(--storagetmp) = '\0';
    do {
        *(--storagetmp) = num % 10 + '0';
    } while ((num /= 10) && (storagetmp >= storage+STORAGE+SIZE-digits));
    return(storage+STORAGE_SIZE-digits);
}
// -------------------------------------------------------------------------


    -Scott