Last active
August 26, 2021 05:38
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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