Forum OpenACS Q&A: Response to Base 62 Converter: 1A to 72

Posted by Michael A. Cleverly on
It's late, but here's a stab at it, that I believe works correctly. It should work for any base (2 through 62). It doesn't check to make sure that the number is really in the base you tell it (so giving it something silly, like base_n_to_decimal FF 2 will give a bogus answer, but, then that's epxected: garbage in, garbage out... :^):

proc base_n_to_decimal {number base_n} {

set base [list 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T
     U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z]
set decimal 0
set power [string length $number]

foreach char [split $number ""] {

incr power -1
set dec_val [lsearch $base $char]
set decimal [expr $decimal + $dec_val * int(pow($base_n,$power))]

return $decimal


It works for your test case:

set mynum "[base62_to_integer 0A 62]"