2010年6月4日 星期五

Catching Integer Overflows in C

Integer Overflows are arithmetic errors. Integers have finite ranges in computers, for example a 32-bit unsigned integer goes from 0 to 0xffffffff. If you add one to 0xffffffff, you get 0 again.

Since the addition operation in the CPU is agnostic to whether the integer is signed or unsigned, the same goes for signed integers. For 32-bit signed integers, the minimum value is 0x80000000 (-2147483648) and the maximum value is 0x7fffffff (2147483647). Note that there is no value than can hold 2147483648, so if you negate (int)0x80000000, you get (int)0x80000000 again. That is something to look out for, because it means abs() returns a negative value when fed -2147483648.

原文出處: http://www.fefe.de/intof.html


沒有留言:

張貼留言