Jump to content

Convert between any positionsystems


imbatmo
 Share

Recommended Posts

i wrote 3 functions to convert integers between positionalsystems (does only work up to 9base system)

; calculates the logarithm to any base (needed for _DecToAny)
Func _Log($iResult, $iBase)
    Return Log($iResult) / Log($iBase)
EndFunc

;Converts a decimal integer to a number of any new positionalsystem
Func _DecToAny($iDec, $iNewSystem)
    Local $iAny = ""
    Local $iIncrease
    Local $iExp = int(_Log($iDec, $iNewSystem))
    While $iExp >= 0
        If $iDec - $iNewSystem^$iExp >= 0 Then
            $iIncrease = int($iDec /  $iNewSystem^$iExp)
            $iAny &= $iIncrease
            $iDec -= $iIncrease * $iNewSystem^$iExp
        Else
            $iAny &= "0"
        EndIf
        $iExp -= 1
    WEnd
    Return $iAny
EndFunc 


;converts a number from any positional system to a decimal integer
Func _AnyToDec($iAny, $iOldSystem)
    Local $iDec = 0
    For $x = 1 To StringLen($iAny)
        $iDec += StringMid($iAny, $x, 1) * $iOldSystem^(StringLen($iAny)-$x)
    Next
    Return $iDec
EndFunc

;converts a number from any positional system to a number of another positional system
Func _AnyToAny($iAny, $iOldSystem, $iNewSystem)
    Return _DecToAny(_AnyToDec($iAny, $iOldSystem), $iNewSystem)
EndFunc


;examples

;converts the decimal integer 14 to Binary system: 1110
MsgBox(0, "", "14 ---> " & _DecToAny(14, 2))

;converts the number 2012 of the 3base system to a decimal integer: 2*27 + 0 + 1*3 + 2*1 = 59
MsgBox(0, "", "2012 ---> " & _AnyToDec("2012", 3))

;converts the number 21 of the 7base system to Binary System: 20 ---> 15(decimal) --> 1111
MsgBox(0, "", "2012 ---> " & _AnyToAny("21", 7, 2))

hope you can find a use for it (i cant so far :P )

the file:

Edited by imbatmo
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...