devxlogo

Add Two Long Numbers Together Without Causing an Overflow Error

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 bitsFunction 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 quickerEnd Function
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist