I would like to print first N numbers in BASE62 encoding. What's wrong in my code?
const char ALPHABET[63] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int main(void) {
int N = 50;
for (int i = 0; i < N; i++) {
int base62 = ALPHABET[i % 62];
printf("Base 62: %s\n", (char*)base62);
}
}
You need to print out string representing the number in base62. For N >= 62, you will have a multi-character string. First, you would need to count the number of digits in the base62 representation and then display character-by-character.
For that, you need to something like this-
// Count the number of characters the number will need
int num_digits(int num) {
int count=0;
while(num > 0) {
num /= 62;
count++;
}
if(count == 0)
count = 1;
return count;
}
int main() {
const char ALPHABET[63] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i, N=100;
char STR[10];
for (i = 0; i < N; i++) {
int num = i;
int digits = num_digits(num);
STR[digits] = '\0';
while(num > 0) {
char base62 = ALPHABET[num % 62];
STR[--digits] = base62;
num /= 62;
}
if(i == 0)
STR[--digits] = ALPHABET[0];
printf("%s\n", i, STR);
}
}