Skip to content

Instantly share code, notes, and snippets.

@jarhill0
Last active April 8, 2019 18:14
Show Gist options
  • Save jarhill0/a85b40f7f55f05024d1975179a2f7c1a to your computer and use it in GitHub Desktop.
Save jarhill0/a85b40f7f55f05024d1975179a2f7c1a to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define DIGITS "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
void my_itoa(int num, char* str, int base) {
if (num < 0) {
num *= -1;
str[0] = '-';
str++;
}
int base_power = 1;
int num_digits = 1;
while (num / base_power > base - 1) {
base_power *= base;
num_digits++;
}
int i = 0;
for (; i < num_digits; i++) {
int digit = (num / base_power) % base;
str[i] = DIGITS[digit];
base_power /= base;
}
str[i] = '\0';
}
int main() {
char word[100];
for (int i = -500; i < 501; i += 5) {
my_itoa(i, word, 10);
printf("%s\n", word);
my_itoa(i, word, 16);
printf("%s\n", word);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment