• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 251
  • Last Modified:

OverFlow problem


I have this code;

Dim MyVal As Long

MyVall = MyVal + (b * (n And &HFF))       '2147481230 + 20202
MyVal = MyVal And &HFFFF

MyVal = 2147481230
b = 111
n = 307382

When it tries to add MyVal to b,n, it produces an overflow.  So I changed the data type to variant but then it had the overflow on the AND part of the code.

Any ideas how I can get around this?
many thanks
1 Solution
Hi TJ_Eng,

You produce an overflow because Long is a signed value and the result of your equations gets larger than 0x7FFF FFFF (max. positive number).

If you define MyVal as Variant VB automatically uses Variant / Double instead of overflowing which cannot be used together with logical operators (And).

You could use another variable for saving the most significant unsigned bit of myval; perform your operation and logically add that bit again. This solution is valid if you only plan to perform hex operations (and, or, not, xor) afterwards (you get a negative decimal number):

Dim Msb as long

Msb = MyVal And &H40000000
MyVal = MyVal and not &H40000000

' Perform your operations
' ...

if (MyVal And &H40000000) And Msb then
    if (MyVal And &HC0000000) = &HC0000000 Then
        ' Error: still an overflow
        MyVal = MyVal Or &H80000000
    End If
    MyVal = MyVal or Msb
end if

Best regards,

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now