Last active
May 9, 2023 08:20
-
-
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
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
#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