Created
June 14, 2011 22:22
-
-
Save kopiro/1026081 to your computer and use it in GitHub Desktop.
Convert any number from base X to base X
This file contains hidden or 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
char* base_converter(char* nbasefrom, int basefrom, int baseto) { | |
const char* SYMBOLS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
if (basefrom<=0 || basefrom>strlen(SYMBOLS) || baseto<=0 || baseto>strlen(SYMBOLS)) { | |
fprintf(stderr, "Base unallowed"); | |
return NULL; | |
} | |
int i, nbaseten=0; | |
if (basefrom!=10) { | |
int sizenbasefrom = strlen(nbasefrom); | |
for (i=0; i<sizenbasefrom; i++) { | |
int mul, mul_ok=-1; | |
for (mul=0; mul<strlen(SYMBOLS); mul++) { | |
if (nbasefrom[i]==SYMBOLS[mul]) { | |
mul_ok = 1; | |
break; | |
} | |
} | |
if (mul>=basefrom) { | |
fprintf(stderr, "Symbol unallowed in basefrom"); | |
return NULL; | |
} | |
if (mul_ok==-1) { | |
fprintf(stderr, "Symbol not found"); | |
return NULL; | |
} | |
int exp = (sizenbasefrom-i-1); | |
if (exp==0) nbaseten += mul; | |
else nbaseten += mul*pow(basefrom, exp); | |
} | |
} else nbaseten = atoi(nbasefrom); | |
if (baseto!=10) { | |
char* nbaseto = malloc(sizeof(char)); | |
int size = 0; | |
while (nbaseten>0) { | |
char* nbaseto_re = realloc(nbaseto, (++size)*sizeof(char)); | |
if (nbaseto_re==NULL) { | |
fprintf(stderr, "Memory error"); | |
return NULL; | |
} | |
nbaseto = nbaseto_re; | |
int mod = nbaseten%baseto; | |
if (mod<0 || mod>=strlen(SYMBOLS)) { | |
fprintf(stderr, "Out of bounds error"); | |
return NULL; | |
} | |
char symbol = SYMBOLS[mod]; | |
nbaseto[size-1] = symbol; | |
nbaseten = (int)nbaseten/baseto; | |
} | |
for (i=0; i<size; i++) nbaseto[i] = nbaseto[size-1-i]; | |
return nbaseto; | |
} else { | |
int nbasetenlen = 0, _nbaseten = nbaseten; | |
while (_nbaseten>0) { | |
nbasetenlen++; | |
_nbaseten/=10; | |
} | |
char* nbaseten_chr = malloc((1+nbasetenlen)*sizeof(char)); | |
sprintf(nbaseten_chr, "%d", nbaseten); | |
return nbaseten_chr; | |
} | |
return "0"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment