View Single Post
  #14   Report Post  
Posted to microsoft.public.excel.programming
Martin Brown Martin Brown is offline
external usenet poster
 
Posts: 230
Default Convert Base 36 to base 10

Rick Rothstein wrote:
Here is the Decimal Data Type version of my function which will handle
up to a 28-digit Base36 number (max "number" is ZZZZZZZZZZZZZZZZZZ)...

Function ConvertBase36ToBase10(Base36Number As String) As Variant
Dim x As Long, Digit As String, Power As Variant
If Len(Base36Number) 18 Or Base36Number Like "*[!0-9A-Za-z]*" Then
ConvertBase36ToBase10 = CVErr(xlErrNum)
Exit Function
End If
For x = Len(Base36Number) To 1 Step -1
Digit = UCase(Mid(Base36Number, x, 1))
If Len(Base36Number) 9 Then
Power = CDec("101559956668416") * (36 ^ (Len(Base36Number) - 9 - x))
Else
Power = 36 ^ (Len(Base36Number) - x)
End If
ConvertBase36ToBase10 = ConvertBase36ToBase10 + CDec(IIf(IsNumeric( _
Digit), Digit, (Asc(Digit) - 55)) * Power)
Next
End Function

Note that the If..Then handling of the exponent for the 36 base number
is necessary because raising any number to a power using the caret
(^(^(^) operator collapses Decimal Data Type values back to Long Data
Type values... the 101559956668416 value is 36 raised to the 9th power.
I also through in some error checking as well.


It may be cleaner to avoid ^ entirely and to do the loop incrementally -
something along the lines of

ConvertBase36ToBase10 = 0
For x = Len(Base36Number) To 1 Step -1
Digit = UCase(Mid(Base36Number, x, 1))
ConvertBase36ToBase10 = ConvertBase36ToBase10*36 +
CDec(IIf(IsNumeric(Digit), Digit, (Asc(Digit) - 55))
Next

Regards,
Martin Brown