Convert any number to any base in C
I've just had a crack at Exercise 3-5. This is the first time too that I have used exit(). Usually I have been returning -1 for an error, or similar. The problem with that however, is the function's return type must be an int. This means, semantically, it would seem the function may be returning an int as part of its intended use. Because this is not the case, I've decided to use exit().
void itob(int num, char str[], int base) {
if (base < 2 || base > 36) {
exit(1);
}
int remainder = num;
int i = 0;
while (remainder > 0) {
int value = remainder % base;
char place;
if (value > 9) {
place = 'A' + value - 10;
} else {
place = '0' + value;
}
str[i++] = place;
remainder /= base;
}
// Our string is in reverse
strrev(str);
str[i] = '\0';
}
Comments
Russell Dias
Posted on Sunday, 5th September 2010 @ 5:55pm.C seems to be treating you well. Must have been a huge change. From being given virtually everything in PHP, to well... practically nothing in C =P
I guess moving to a complied language seems logical enough. Now I just need to find the time to do so.
Leave a Comment
Note: Your comment may require approval before it is posted to the site.