Sign in to follow this  
Followers 0
Caja

convert from base 10 to base 36

4 posts in this topic

Hi everyone,

I figured out how to do the reverse from base-36 to base-10 but having difficulty wrapping my head around how to convert from base-10 to base-36. Any help would be much appreciated.

#include <Array.au3>
Dim $array[36] = ["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"]
Dim $sum = ""
Dim $str = "GNTHQ"

$strLen = StringLen($str)
For $i = 0 To ($strLen-1)
    $index = _ArraySearch($array, StringMid($str, $i+1, 1))
    $sum = $sum + ($index * (36^(($strLen-1)-$i)))
Next

MsgBox(0, "convert from base-10 to base-36", "Base-36 : " & $str &@CR& "Base-10 : " & $sum)

Share this post


Link to post
Share on other sites



For anyone interested, I've figured it out... very proud of myself ;)

#include <String.au3>
Dim $sum = ""
Dim $str = "27985166"

For $i = (36-1) To 0 Step -1
    $single = Int($str / (36^$i))
    $str = $str - ($single * (36^$i))
    If $single > 0 And $single < 10 Then
        $sum = Chr(48 + $single) & $sum
    ElseIf $single >= 10 Then
        $sum = Chr(55 + $single) & $sum
    EndIf
Next
$sum = _StringReverse($sum)
MsgBox(0, "convert from base-10 to base-36", "Base-36 : " & $sum)

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

The routine I use to convert bases agrees with your result!

Nicely done, and welcome to the forum ;)

Edit: Oops! lol "Member since 13-December 07" You're the silent type!

Edit2: I use this which works for any combination of Binary, Octal, Decimal, Hexadecimal, or as I've just noticed, anything up to base 36:

$result = _BaseToBase("F16", 16, 8) ; hex to octal
MsgBox(0,"",$result)
;===================================================================================================================================
Func _BaseToBase($sIn, $iBaseIn, $iBaseOut)
    Local $sOut = 0
    If $iBaseIn <> 10 Then ; iBaseIn to decimal
        $aVal = StringSplit($sIn, "")
        For $x = 1 to $aVal[0]
         $iDec = Asc($aVal[$x]) - (48 + ($aVal[$x] > "9") * 7)
            $sOut += $iDec * ($iBaseIn ^ ($aVal[0] - $x))
        Next
        $sIn = $sOut
    EndIf
    If $iBaseOut <> 10 Then ; decimal to iBaseOut
        $sOut = ""
        While $sIn >= 1
            $x = Mod($sIn, $iBaseOut)
            $sOut = Chr($x + 48 + ($x > 9) * 7) & $sOut
            $sIn = ($sIn - $x) / $iBaseOut
        WEnd
    EndIf
    Return $sOut
EndFunc
Edited by Spiff59

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0