PB5 : Convert Value to Base N
Posted: Tue Feb 26, 2013 11:24 pm
- Base N conversion functions
BaseN.pbi
BaseN.pbi
Code: Select all
Procedure.s IntToBaseN(value.i, baseChars.s)
; convert integer number to base N (returns EMPTY if error)
Protected targetBase = Len(baseChars)
Protected result.s = ""
If targetBase < 2 Or targetBase > SizeOf(value)*4 : ProcedureReturn "" : EndIf
Repeat
result = PeekS(@baseChars + value % targetBase, 1) + result
value = value/targetBase
Until (value <= 0)
ProcedureReturn result
EndProcedure
Procedure.i BaseNtoInt(strValue.s, baseChars.s)
; convert base N number to integer (returns -1 if error)
Protected targetBase = Len(baseChars)
Protected result = 0
If targetBase < 2 Or targetBase > SizeOf(result)*4 : ProcedureReturn -1 : EndIf
For i = 1 To Len(strValue)
v = FindString(baseChars, Mid(strValue, i, 1)) - 1
If v = -1 : ProcedureReturn -1 : EndIf ;
result * targetBase + v
Next
ProcedureReturn result
EndProcedure
Code: Select all
Debug IntToBaseN(101,"01") ;<---- Bin = base2
For i=0 To 15
Debug IntToBaseN(i,"0123456789ABCDEF") ;<---- Hexa = base16
Next
customBase.s="ABCDEFGHIJKLMNOPQRSTUVWXYZ_"
Debug IntToBaseN(7561231232,customBase); <--- custom Base
Debug BaseNtoInt("TNZVJIF",customBase)
CompilerIf #PB_Compiler_Processor=#PB_Processor_x64
If (BaseNtoInt(IntToBaseN(9223372036854775807,customBase),customBase)=9223372036854775807)
Debug "Result is correct - BaseN functions work!"
EndIf
CompilerElse
If (BaseNtoInt(IntToBaseN(2147483647,customBase),customBase)=2147483647)
Debug "Result is correct - BaseN functions work!"
EndIf
CompilerEndIf