Created
July 5, 2026 05:36
-
-
Save miura1729/36bb01b44775e11cf074c43b3ccc57c6 to your computer and use it in GitHub Desktop.
fast (maybe) itoa without division
This file contains hidden or 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
| #include <stdio.h> | |
| char *itoa(short n, char *out) { | |
| char *orgout = out; | |
| static short tab[] = {1000, 100, 10, 1}; | |
| int cn; | |
| cn = 0; | |
| while (n >= 10000) { | |
| cn++; | |
| n -= 10000; | |
| } | |
| if (cn > 0) { | |
| *out++ = (cn + '0'); | |
| } | |
| for (int i = 0; i < 4; i++) { | |
| short num = tab[i]; | |
| short num5xx = (num << 2) + num; | |
| cn = 0; | |
| if (n >= num5xx) { | |
| cn += 5; | |
| n -= num5xx; | |
| } | |
| short num3xx = (num << 1) + num; | |
| if (n >= num3xx) { | |
| cn += 3; | |
| n -= num3xx; | |
| } | |
| if (n >= num) { | |
| cn++; | |
| n -= num; | |
| } | |
| if (n >= num) { | |
| cn++; | |
| n -= num; | |
| } | |
| if (cn > 0 || out != orgout) { | |
| *out++ = (cn + '0'); | |
| } | |
| } | |
| if (out == orgout) { | |
| *out++ = '0'; | |
| } | |
| *out = '\0'; | |
| return orgout; | |
| } | |
| void main(void) { | |
| char buf[6]; | |
| puts(itoa(32767, buf)); | |
| puts(itoa(32766, buf)); | |
| puts(itoa(10001, buf)); | |
| puts(itoa(10000, buf)); | |
| puts(itoa(12345, buf)); | |
| puts(itoa(5678, buf)); | |
| puts(itoa(9012, buf)); | |
| puts(itoa(9999, buf)); | |
| puts(itoa(0, buf)); | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment