unsigned digits10(unsigned v) {
if (v < 10) return 1;
if (v < 100) return 2;
if (v < 1000) return 3;
if (v < 1000000000) {
if (v < 100000000) {
if (v < 1000000) {
if (v < 10000) return 4;
return 5 + (v >= 100000);
}
return 7 + (v >= 10000000);
}
return 9;
}
return 10;
}
int Itoa(char *dst, unsigned dstlen, int svalue) {
static const char digits[201] =
"0001020304050607080910111213141516171819"
"2021222324252627282930313233343536373839"
"4041424344454647484950515253545556575859"
"6061626364656667686970717273747576777879"
"8081828384858687888990919293949596979899";
int negative;
unsigned value;
if (svalue < 0) {
value = -svalue;
negative = 1;
} else {
value = svalue;
negative = 0;
}
/* Check length. */
unsigned const length = digits10(value)+negative;
if (length >= dstlen) return 0;
/* Null term. */
unsigned next = length;
dst[next] = '\0';
next--;
while (value >= 10) {
int const i = (value % 100) * 2;
value /= 100;
dst[next] = digits[i + 1];
dst[next - 1] = digits[i];
next -= 2;
}
/* Handle last 1 digits. */
if (value > 0 || length == 1 ) {
dst[next] = '0' + value;
}
/* Add sign. */
if (negative) dst[0] = '-';
return length;
}