Arithmetic operation resulted in an overflow. (Adding integers)

前端 未结 8 1703
既然无缘
既然无缘 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 :)

提交回复
热议问题