Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB
Expertise: Advanced
Jul 5, 2005

Add Two Long Numbers Together Without Causing an Overflow Error

This function adds two long numbers together as if they were unsigned, and does not cause an overflow error. You may need this when implementing the SHA-1 Hashing function.

' Add two numbers together, without overflow or signed bits
Function FullAdd(ByVal x As Long, ByVal y As Long) As Long
    Dim z As Long
    Dim z1 As Boolean, z2 As Boolean, c2 As Boolean
    ' First, add the two numbers without their top two bits (prevents overflow)
    z = (x And &H3FFFFFFF) + (y And &H3FFFFFFF)
    ' Perform a full addition on the 31st bit (carry is in z31)
    z1 = CBool(z And &H40000000) Xor (CBool(y And &H40000000) Xor _
   CBool(x And &H40000000))
    c2 = (CBool(y And &H40000000) And CBool(x And &H40000000)) Or _
   (CBool(z And &H40000000) _
   And CBool(x And &H40000000)) _
   Or (CBool(y And &H40000000) And CBool(z And &H40000000))

    ' Now perform a full addition for the 32nd bit (but we don't care about the _
   carry bit)
    z2 = c2 Xor (CBool(y And &H80000000) Xor CBool(x And &H80000000))

    ' If you wanted to test for an overflow you could test the carry bit here and _
   raise the appropriate error
    'If (CBool(y And &H80000000) And CBool(x And &H80000000)) Or _
   (c2 And CBool(x And
   &H80000000)) _
    '        Or (CBool(y And &H80000000) And c2) Then Err.Raise6 , , _
   "Overflow in FullAdd"

    ' Now we can chuck it all together
    FullAdd = (z And &H3FFFFFFF) Or (z1 And &H40000000) Or (z2 And &H80000000)

    ' nb. an alternative would have been to add the first and second 16-bit groups
    ' separately. Although neater, this would have need a 16-leftshift and 16-rightshift
    ' As shifts are not natively supported, this method is quicker

End Function
David Day
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.