Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save miura1729/36bb01b44775e11cf074c43b3ccc57c6 to your computer and use it in GitHub Desktop.

Select an option

Save miura1729/36bb01b44775e11cf074c43b3ccc57c6 to your computer and use it in GitHub Desktop.
fast (maybe) itoa without division
#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