1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
/*
myiota:
converts an int in [0,4095] range into a 4 chars string left filled with 0
*outstr should points on a string buffer of at least 5 chars
*/
void myitoa(unsigned short num,char *outstr)
{
#define BASE (10)
int q, r ;
char *s = outstr + 3 ;
outstr[0] = '0' ;
outstr[1] = '0' ;
outstr[2] = '0' ;
outstr[3] = '?' ;
outstr[4] = '\0' ;
if (num > 4095)
return ;
do {
r = num % BASE ;
q = num / BASE ;
*s-- = r + '0' ;
num = q ;
}
while (num) ;
#undef BASE
}
#ifdef TEST
#include <stdio.h>
#include <string.h>
int main (void)
{
struct test
{
int n;
int val;
char const *s;
int ret;
};
static const struct test a[]=
{
{10, 0, "0000", 0},
{11, 4095, "4095", 0},
{20, 4096, "000?", 0},
{20, -1 , "000?", 0},
};
size_t i;
#define N(a) (sizeof(a)/sizeof*(a))
for (i=0; i < N(a); i++)
{
struct test const *p = a + i;
char s[8] = "********";
myitoa(p->val, s);
if (strcmp (s, p->s) != 0)
{
printf ("ERR at test %d\n", p->n);
break;
}
}
if (i == N(a))
{
puts ("P A S S E D");
}
return 0;
}
#endif |