Search code examples
binaryradix

Convert any base to binary


Is there a algorithm or formula that can convert any base n, say 2 to 36, to binary? I've looked around the web and can't quite find what I'm looking for.


Solution

  • Something to get you started.

    unsigned strtou(const char *s, unsigned base) {
      unsigned y = 0;
      while (*s) {
         unsigned digit;
         if (isdigit(*s)) digit = ch - '0';
         else if (isupper(*s)) digit = ch - 'A' + 10;
         else if (islower(*s)) digit = ch - 'a' + 10;
         else Handle_IllegalDigit();
         if (digit >= base) Handle_IllegalDigit();
    
         y = y*base + digit;
         s++;
      }
      return y;
    }