Thursday, October 2, 2008

VBScript Adding Large Hex Strings

This function is an example of how to add two large hex strings together keeping them as string values:
Function HexAdd(ByVal strNum1, ByVal strNum2)
size1 = Len(strNum1)
size2 = Len(strNum2)
If (size1 <> size2) Then
If (size1 > size2) Then
strNum2 = String(size1 - size2, "0") + strNum2
size2 = size1
Else
strNum1 = String(size2 - size1, "0") + strNum1
size1 = size2
End If
End If
' Begin adding
Dim i
Dim ret
Dim carry
Dim sum
ret = ""
i = CDbl(0)
carry = 0
For i = 1 To size1 '199999999999999999999998
a = "&H" & CStr(Mid(strNum1, size1 - i + 1, 1))
b = "&H" & CStr(Mid(strNum2, size1 - i + 1, 1))
sum = CInt(a) + CInt(b) + carry
ret = Hex(CStr(sum Mod 16)) & ret
carry = Fix(sum / 16)
Next
If (carry > 0) Then
ret = CStr(Hex(carry)) & ret
End If
HexAdd = ret
End Function

Call it like this:

ret = HexAdd("FFFFF", "123456789ABCDEF")

No comments: