SubName: toDecimal, fromDecimal, fromDecimal2, toDecimal2, FromTo
Author: Unknown + derez
Description: Convert number to other base
Here are 3 subs that perform base conversion to and from decimal to base less then 10 - returns int, and to larger base - returns string.
Edit: added toDecimal2 to convert base greater then 10 (string) to decimal.
Edit: toDecimal2 improved and FromTo added
Tags : base conversion
Author: Unknown + derez
Description: Convert number to other base
Here are 3 subs that perform base conversion to and from decimal to base less then 10 - returns int, and to larger base - returns string.
Edit: added toDecimal2 to convert base greater then 10 (string) to decimal.
Edit: toDecimal2 improved and FromTo added
B4X:
'Convert integer in any base (2<=b<=10) to decimal integer.
Sub toDecimal( n As Int, base As Int) As Int
Dim result As Int = 0
Dim multiplier As Int = 1
Do While n > 0
result = result + (n Mod 10) * multiplier
multiplier = multiplier * base
n = n / 10
Loop
Return result
End Sub
'Convert decimal integer to any base (2<=b<=10) .
Sub fromDecimal(n As Int, base As Int) As Int
Dim result As Int = 0
Dim multiplier As Int = 1
Do While n > 0
result = result + (n Mod base) * multiplier
multiplier = multiplier * 10
n = n / base
Loop
Return result
End Sub
'Convert decimal integer to any base up to 20, returns string.
Sub fromDecimal2(n As Int, base As Int) As String
Dim chars As String ="0123456789ABCDEFGHIJ"
Dim result As String = ""
Do While n > 0
result = chars.charAt(n Mod base) & result
n = n / base
Loop
Return result
End Sub
'Convert any base up to 20 to decimal integer
Sub toDecimal2( n As String, base As Int) As Int
n = n.ToUpperCase
Dim result As Int = 0
Dim st As String
Dim chars As String ="0123456789ABCDEFGHIJ"
Dim k As Int = n.length - 1
Dim multiplier As Int = 1
For i = k To 0 Step -1
st = n.CharAt(i)
result = chars.IndexOf(st) * multiplier + result
multiplier = multiplier * base
Next
Return result
End Sub
'Convert from one base to another, both must be less or equal to 10.
Sub FromTo(n As Int, frombase As Int, tobase As Int) As Int
Dim t As Int = todecimal(n,frombase)
Return fromDecimal(t,tobase)
End Sub
Tags : base conversion
Last edited: