Numeric Base Conversions (2 thru 36)
Posted: Mon Feb 23, 2004 11:43 pm
Code updated for 5.20+
Here are a couple of routines that may come in handy:
Here are a couple of routines that may come in handy:
Code: Select all
; Commonly used BASE constants for use in
; the base argument of Int2Base and Base2Int
Enumeration
#BASEMIN = 2
#BINBASE = 2
#OCTBASE = 8
#HEXBASE = 16
#BASEMAX = 36
EndEnumeration
; Convert an integer to a given base
; Supports bases 2 thru 36
Procedure.s Int2Base(value, base)
Protected result.s
If (base >= #BASEMIN) & (base <= #BASEMAX)
Protected i
Repeat
i = (value % base) + 1
value = (value / base)
result = Mid("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", i, 1) + result
Until value = 0
EndIf
ProcedureReturn result
EndProcedure
; Convert a string value from a given base To an integer
; Supports bases 2 thru 36
Procedure Base2Int(value.s, base)
Protected result
result = 0
If (base >= #BASEMIN) & (base <= #BASEMAX)
Protected i, c
For i = 1 To Len(value)
c = FindString("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", UCase(Mid(value, i, 1)), 1)
; Return -1 If character is not supported by base
If c > base
result -1
Break
EndIf
result = (result * base) + (c - 1)
Next i
EndIf
ProcedureReturn result
EndProcedure
If OpenConsole()
For i = 240 To 255
PrintN("----------")
PrintN("Bin or Base 2: " + Int2Base(i, #BINBASE))
PrintN("Oct or Base 8: " + Int2Base(i, #OCTBASE))
PrintN("Dec or Base 10: " + Str(i))
PrintN("Hex or Base 16: " + Int2Base(i, #HEXBASE))
Next i
Print("Press a key... ")
Repeat : Until Inkey()
CloseConsole()
EndIf