Arithmetic operation resulted in an overflow. (Adding integers)

前端 未结 8 1660
既然无缘
既然无缘 2020-12-20 11:16

I can\'t understand this error:

In this call to method SetVolume, Volume = 2055786000 and size = 93552000. Volume is an Integer pr

相关标签:
8条回答
  • 2020-12-20 11:25

    For simplicity I will use bytes:

    byte a=250;
    byte b=8;
    byte c=a+b;
    

    if a, b, and c were 'int', you would expect 258, but in the case of 'byte', the expected result would be 2 (258 & 0xFF), but in a Windows application you get an exception, in a console one you may not (I don't, but this may depend on IDE, I use SharpDevelop).

    Sometimes, however, that behaviour is desired (e.g. you only care about the lower 8 bits of the result).

    You could do the following:

    byte a=250;
    byte b=8;
    
    byte c=(byte)((int)a + (int)b);
    

    This way both 'a' and 'b' are converted to 'int', added, then casted back to 'byte'.

    To be on the safe side, you may also want to try:

    ...
    byte c=(byte)(((int)a + (int)b) & 0xFF);
    

    Or if you really want that behaviour, the much simpler way of doing the above is:

    unchecked
    {
        byte a=250;
        byte b=8;
        byte c=a+b;
    }
    

    Or declare your variables first, then do the math in the 'unchecked' section.

    Alternately, if you want to force the checking of overflow, use 'checked' instead.

    Hope this clears things up.

    Nurchi

    P.S.

    Trust me, that exception is your friend :)

    0 讨论(0)
  • 2020-12-20 11:25

    Maximum value fo int is 2147483647, so 2055786000+93552000 > 2147483647 and it caused overflow

    0 讨论(0)
  • 2020-12-20 11:32

    The maximum size for an int is 2147483647. You could use an Int64/Long which is far larger.

    0 讨论(0)
  • 2020-12-20 11:33
    int.MaxValue = 2147483647
    2055786000 + 93552000 = 2149338000 > int.MaxValue
    

    So you cannot store this number into an integer. You could use Int64 type which has a maximum value of 9,223,372,036,854,775,807.

    0 讨论(0)
  • 2020-12-20 11:43

    The result integer value is out of the range which an integer data type can hold.

    Try using Int64

    0 讨论(0)
  • 2020-12-20 11:46

    The maximum value of an integer (which is signed) is 2147483647. If that value overflows, an exception is thrown to prevent unexpected behavior of your program.

    If that exception wouldn't be thrown, you'd have a value of -2145629296 for your Volume, which is most probably not wanted.

    Solution: Use an Int64 for your volume. With a max value of 9223372036854775807, you're probably more on the safe side.

    0 讨论(0)
提交回复
热议问题