Skip to content

Instantly share code, notes, and snippets.

@elazarl
Last active May 9, 2023 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elazarl/daa52e10fae228b93828703cffdf55db to your computer and use it in GitHub Desktop.
Save elazarl/daa52e10fae228b93828703cffdf55db to your computer and use it in GitHub Desktop.
Small standalone stupid function to convert integer value to string, for code with zero library support
#include <stdint.h>
#include <stdio.h>
char *sprint_int_(char *out, uint64_t a, uint64_t base) {
char itoc[] = "0123456789abcdef";
char *orig_out = out;
uint64_t a_ = a;
int i = 0;
while (a_ >= base) {
a_ /= base;
i++;
}
out[i + 1] = '\0';
while (i >= 0) {
out[i] = itoc[a % base];
i--;
a /= base;
}
return orig_out;
}
char *sprint_int(char *out, uint64_t a) { return sprint_int_(out, a, 10); }
char *sprint_hex(char *out, uint64_t a) { return sprint_int_(out, a, 16); }
int main() {
char buf[100];
printf("%s\n", sprint_int(buf, 12345));
printf("%s\n", sprint_int(buf, 0xfffffff));
printf("%s\n", sprint_hex(buf, 0xfffffff));
printf("%s\n", sprint_int(buf, 0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment