Last active
December 14, 2020 19:47
-
-
Save fernandolopez/799aa0de7402d40c9126 to your computer and use it in GitHub Desktop.
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 <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <math.h> | |
#include <assert.h> | |
char *digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
char *base(int nro, int base, char *buff){ | |
int length; | |
int mod; | |
int i; | |
if (nro == 0){ | |
strcpy(buff, "0"); | |
return buff; | |
} | |
else{ | |
// Calculo cuantos dígitos son necesarios | |
length = log(nro) / log(base) + 1; | |
} | |
buff[length] = '\0'; // Terminación del string | |
i = length - 1; // Lo cargamos al revés | |
while (nro > 0) { | |
mod = nro % base; | |
nro = nro / base; | |
buff[i] = digits[mod]; | |
i--; // Decremento hasta llegar a cero | |
} | |
buff[i] = 0; | |
return buff; | |
} | |
int main(){ | |
char str[256]; | |
printf("%s\n", base(50, 2, str)); | |
printf("%s\n", base(50, 3, str)); | |
printf("%s\n", base(50, 10, str)); | |
printf("%s\n", base(50, 16, str)); | |
printf("%s\n", base(50, 36, str)); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment