Print first N numbers in BASE62

523 Views Asked by At

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);
    }
}
3

There are 3 best solutions below

1
sray On BEST ANSWER

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);
   }
}
2
Peter G. On

ALPHABET is an array of chars, so you should be fine with using char base 62 ... and printf("Base 62: %c\n", base62);

Casting a normal int to pointer and passing that to printf as in the original code will lead to printf making invalid memory reads (undefined behavior).

7
chux - Reinstate Monica On

After accept simplification

As Cool Guy commented, printf("Base 62: %s\n", (char*)base62);, will not convert an int into the desired array of characters. Below code breaks down the value, one base-62 character at a time.

void print_base(unsigned n, unsigned base) {
  static const char ALPHABET[] =
      "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  if (n >= base) {
    print_base(n / base, base);
  }
  fputc(ALPHABET[n % base], stdout);
}

#include <stdio.h>
int main(void) {
  print_base(100, 10); // 100
  puts("");
  print_base(100, 16); // 64
  puts("");
  print_base(100, 62); // 1C
  puts("");
  return 0;
}