Base10 to Base...
Posted: Wed May 25, 2011 8:06 pm
I am not sure how many of you will find these functions useful, but I am posting them anyway. I know there are built in functions for converting back and forth from Hex/Base64/Base2(Binary)...but these functions seem to be very unfriendly to variables.
So, I designed these 2 procedures for converting back and forth...as well as some examples on usage...
First, converting to a base...I did this so there could be other bases besides the ones listed above...
Then converting from any base back to Base 10 (regular integer)...
And here, are some examples of how to use the functions in other functions...
I am showing Hex and Base64...just for examples
The 3rd parameter in Base2Int is #False by default, that means Case Insensitive. That is fine for HEX, and BIN, but not for Base64...so we need to set the Case Sensitive to #True
So, I designed these 2 procedures for converting back and forth...as well as some examples on usage...
First, converting to a base...I did this so there could be other bases besides the ones listed above...
Code: Select all
#_NUM_BASE_10 = "0123456789" ; This is just to give it a default
Procedure.s Int2Base(InVal.l, Valid.s=#_NUM_BASE_10)
Base.l = Len(Valid)
RemVal = InVal
OutVal.s
While RemVal
OutVal = Mid(Valid, ((RemVal % Base) + 1), 1) + OutVal
RemVal = ((RemVal-(RemVal % Base)) / Base)
Wend
If Not OutVal
OutVal = "0"
EndIf
ProcedureReturn(OutVal)
EndProcedure
Code: Select all
#_NUM_BASE_10 = "0123456789" ; This is just to give it a default
Procedure.l Base2Int(InVal.s, Valid.s=#_NUM_BASE_10, UseCase=#False)
Base.l = Len(Valid)
If Not UseCase
Valid = UCase(Valid)
InVal = UCase(InVal)
Debug "Not Case Sensitive"
EndIf
For i = 1 To Len(InVal)
Chk.s = Mid(InVal, i, 1)
Pos = FindString(Valid, Chk, 1)
If Not Pos
Debug "ERROR: Unsupported Character at Position " + Str(i)
Break
Else
OutVal = (OutVal * Base) + (Pos - 1)
EndIf
Next
ProcedureReturn(OutVal)
EndProcedure
I am showing Hex and Base64...just for examples
Code: Select all
#_NUM_BASE_16 = "0123456789ABCDEF"
#_NUM_BASE_64 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"
Procedure Hex2Int(HexIn.s)
ProcedureReturn(Base2Int(HexIn, #_NUM_BASE_16))
EndProcedure
Procedure.s Int2Hex(InVal)
ProcedureReturn(Int2Base(InVal, #_NUM_BASE_16))
EndProcedure
Procedure Base64ToInt(B64In.s)
ProcedureReturn(Base2Int(B64In, #_NUM_BASE_64, #True))
EndProcedure
Procedure.s Int2Base64(InVal)
ProcedureReturn(Int2Base(InVal, #_NUM_BASE_64))
EndProcedure