OverFlow problem

Hi,

I have this code;

Dim MyVal As Long

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

where,
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
TJ_EngAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MaximKammererCommented:
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
' ...

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

Best regards,
Maxim
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic Classic

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.