/* Exercise compiler’s division-by-a-constant optimizations. GCC for amd64 does fine, while avr-gcc 4.9.2 punts to __divmodhi4: avr-gcc -g -c -mmcu=atmega328p -O5 -Wa,-adlhns=div10.lst div10.c See for some other things it could maybe do instead. */ static int inner_utoa(int n, char *d, char rv) { *d++ = '0' + n % 10; n /= 10; return n ? inner_utoa(n, d, rv + 1) : rv + 1; } static void reverse(char *s, char len) { char *t = s + len; while (--t > s) { char tmp = *s; *s = *t; *t = tmp; s++; } } void outer_utoa(int n, char *d) { char len = inner_utoa(n, d, 0); reverse(d, len); d[(int)len] = '\0'; } #ifdef __linux__ #include #include int main(int argc, char **argv) { char buf[99]; int n = atoi(argv[1]); outer_utoa(n, buf); printf("%d == \"%s\"\n", n, buf); return 0; } #endif