Search code examples
vb.netexceptionoverflowmultiplication

Why does this multiplication cause an OverflowException?


My code tries to multiply 12303 by 174596.

Any decent calculator is capable of providing an answer to this, so why do I get an OverflowException? It also happens when I execute it directly in the Immediate Window.

The code is meant to determine the position of a certain value in a binary file. The file itself is 7 Gb in size.

Is there any way to solve this?

Dim position As Long = hisFileHeader.StreamStartDataPosition + 
  (TSIdx * hisFileHeader.StreamDataBlockSize)

tsidx has a value of 12303 and StreamDataBlockSize has a value of 174596

screenshot


Solution

  • I'm guessing that tsidx and StreamDataBlockSize are Integer types. The largest number an Integer type can hold is 2,147,483,647. The multiplication in brackets is then done expecting an integer result, but the answer is out of the range of Integer types. Change your code to ..

    Dim position As Long = hisFileHeader.StreamStartDataPosition + (CLng(TSIdx) * hisFileHeader.StreamDataBlockSize)
    

    and the multiplication will be done with the expectation of a Long type.