Skip to content

Instantly share code, notes, and snippets.

@kimbo
Created February 6, 2019 21:22
Show Gist options
  • Save kimbo/9985180b170c0bd42a42e702a67a0063 to your computer and use it in GitHub Desktop.
Save kimbo/9985180b170c0bd42a42e702a67a0063 to your computer and use it in GitHub Desktop.
Convert an int to a char * pointer
/*
* itoa - convert an int to a str with the given base.
* My own implementation with LOTS of explanation
*
*/
char *itoa(int val, int base) {
// make sure base is supported
if (base < 2 || base > 16) {
return NULL;
}
// NUMBERS to use for lookups
static char NUMBERS [] = "0123456789abcdef";
// use newstr to store newly built string
static char newstr[32] = { '\0' };
// starting index
// leave last char as 0, '\0', etc
int i = 30;
// while we still have more of val to process,
// and while we haven't got the the beginning of
// our new str (ran out of space)
while (val && i) {
// val % base --> remainder is the value of the next digit
// for example, if val is 14 and we're doing decimal (base 10)
// then the next_digit would be 4.
int next_digit = val % base;
newstr[i] = NUMBERS[next_digit];
// move to next index in newstr
// (actually previous index, or next index,
// but we're going backwars
i--;
// move to the next digit in val
// ex: move from tens digit to ones digit
val = val / base;
}
// return pointer to first letter of newstr
// since we decremented i (i--) at the end of
// the loop, its now pointing at nothing.
// we have to return address of newstr[i + 1] to
// get the last char we assigned it (which should be
// what the newstr starts with, if that makes sense)
return &newstr[i + 1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment