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

Posted by Bob OConnor on

I need TCL code to convert the two digit code used in the bboard sort_key to an integer. This character code is base 62, starting like this

`00.01...09.0A...0Z.0a...0z.10.11`

In other words, 0-9,A-Z,a-z for each character field. There must be a simple procedure like

```set mynum "[base62_to_integer 0A]"
10
```

Thank you.
-Bob

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]"
10
Posted by Michael A. Cleverly on
Oops. Your test case works, but only if you call the procedure by the right name. base_n_to_decimal (not base62_to_integer). It's late. Time for bed. :^)
Posted by Michael A. Cleverly on
I've posted an expanded conversion proc over on the Tcl'ers Wiki at http://mini.net/cgi-bin/wikit/1067.html.