Skip to content

Instantly share code, notes, and snippets.

@madex
Last active August 26, 2021 05:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madex/c5cd5c6a23965a845d6e to your computer and use it in GitHub Desktop.
Save madex/c5cd5c6a23965a845d6e to your computer and use it in GitHub Desktop.
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