Skip to content

Instantly share code, notes, and snippets.

@madex madex/itoaFixedWidth.c
Last active Aug 29, 2015

Embed
What would you like to do?
Fast 32bit signed itoa without division and with fixed width (base 10) filled up with spaces.
char *itoaFixedWidth(int32_t zahl) {
static uint32_t subtractors[] = {1000000000, 100000000, 10000000, 1000000,
100000, 10000, 1000, 100, 10, 1};
static char string[12];
char n, *str = string, sign = zahl < 0 ? '-' : ' ';
uint32_t *sub = subtractors;
uint32_t u = zahl < 0 ? (uint32_t) -zahl : (uint32_t) zahl;
uint8_t i = 10;
*str++ = ' ';
while (i > 1 && u < *sub) {
i--;
sub++;
*str++ = ' ';
}
*(str-1) = sign;
while (i--) {
n = '0';
while (u >= *sub) {
u -= *sub;
n++;
}
*str++ = n;
sub++;
}
*str = 0;
return string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.