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
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may