• Welcome to Valhalla Legends Archive.
 

BigNumber class

Started by CupHead, December 12, 2003, 08:27 PM

Previous topic - Next topic

CupHead

Some quick class I whipped up while talking to Spht about how VB needs to be able to handle large numbers.  Obviously not complete (no other operators and no comparisons), but a decent start if anyone wants to finish it.



' cBigNumber.cls

Option Explicit

Private byteArray(100) As Byte

Public Sub SetNumber(ByVal Number As String)
   Call Clear
   
   Dim i As Integer
   For i = 1 To Len(Number)
       byteArray(99 - Len(Number) + i) = Asc(Mid(Number, i, 1)) - Asc("0")
   Next i
End Sub

Public Function GetNumber() As String
   Dim i As Integer
   For i = 0 To 99
       GetNumber = GetNumber & Chr(byteArray(i) + Asc("0"))
   Next i
   
   While Left(GetNumber, 1) = "0"
       GetNumber = Right(GetNumber, Len(GetNumber) - 1)
   Wend
End Function

Public Function Add(ByVal NumberToAdd As String)
   Dim i As Integer, TempArray(100) As Byte
   Dim Result As Byte, Carry As Boolean
   
   For i = 1 To Len(NumberToAdd)
       TempArray(99 - Len(NumberToAdd) + i) = Asc(Mid(NumberToAdd, i, 1)) - Asc("0")
   Next i

   For i = 99 To 0 Step -1
       Result = IIf(Carry, byteArray(i) + TempArray(i) + 1, byteArray(i) + TempArray(i))
       Carry = False
       
       If Result >= 10 Then
           Carry = True
           Result = Result Mod 10
       End If
       
       byteArray(i) = Result
   Next i
End Function

Private Function Clear()
   Dim i As Integer
   For i = 0 To 99
       byteArray(i) = 0
   Next i
End Function