String Math

Squirm
02-05-2003, 03:08 PM
String Math Part II

Attached is a module containing a few string math functions:

StrAdd
takes two strings, adds them, and returns the result in a string
StrSub
takes two strings, subtracts the second from the first and returns the result in a string
StrMult
takes two strings, multiplies them together and returns the result in a string
StrDiv
takes two strings, divides the first by the second and returns the integer portion of the result in a string
StrMod
takes two strings, divides the first by the second and returns the remainder in a string
StrPow
takes two strings, raises the first to the power of the second and returns the result in a string
StrGT
takes two strings, compares them, and returns True if the first is greater than the the second and False otherwise
StrTrim
takes one string, removes the leading zeros from the beginning of it and returns the result in a string


Its also has comments, hopefully they will be of help.
I had a stab at doing some bitwise functions but quickly realised that is a huge undertaking.
The functions provided work only with positive integers, no fractional/decimal numbers or negatives.
Other than that, the only limit to number size is the limit of a string. Or your patience.

:)

Deadalus
10-15-2004, 02:59 PM
The module that Squirm posted seems to contain an error, that is keeping the StrMult function (and the procedures that use it) from returning the right results. Adding one line should fix it.
Public Function StrMult(sA As String, sB As String) As String
Dim i As Integer, j As Integer
Dim iLenA As Integer, iLenB As Integer
Dim iTemp As Integer, iCarry As Integer
Dim sOut As String, sTemp As String

'Again, I'm using the math tecniques I got taught at school
'Namely, long multiplication

'Calculate once and store, more efficient
iLenA = Len(sA)
iLenB = Len(sB)

'Pad out the shorter string with leading 0s
If (iLenA > iLenB) Then
sB = String$(iLenA - iLenB, "0") & sB
ElseIf (iLenB > iLenA) Then
sA = String$(iLenB - iLenA, "0") & sA
iLenA = iLenB
End If

'We dont preallocate space because we'll be calling the StrAdd function later

For i = iLenA To 1 Step -1
'This was missing.
'The carry-variable should be emptied when going to a new 'line'
iCarry = 0

'Preallocate space for this 'line'
sTemp = Space(iLenA + 1)
For j = iLenA To 1 Step -1

'Calculate
iTemp = ((Asc(Mid$(sA, i, 1)) - 48) * (Asc(Mid$(sB, j, 1)) - 48)) + iCarry
'Save the 'units' portion
Mid$(sTemp, j, 1) = iTemp Mod 10
'Carry the 'tens' portion
iCarry = iTemp \ 10
Next j

If iCarry Then sTemp = iCarry & sTemp
'Multiply by 10^digitnumber (from the right) then add
sOut = StrAdd(sOut, Trim$(sTemp) & String$(iLenA - i, "0"))
DoEvents
Next i

StrMult = StrTrim(sOut)
End Function

Cerian Knight
12-02-2008, 03:52 PM
Additional notes on cleanup and optimization in post #3 here:
http://www.xtremevbtalk.com/showthread.php?t=302558

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum