Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

If b = 0x7fffffff and c = 0x7fffffff, b and c both fit in 31 bits, and b + c overflows to -2 in signed int32 twos-complement math (I think).

If b = 0x40000000 and c = 0x40000000, b and c both fit in 31 bits, and b + c overflows to -2147483648 in signed int32 twos-complement math (I think).

Maybe the definition of "32 bit integer type" you're using is meant to encompass only 32 bits as all unsigned (but then there are a - b terms that would overflow if b > a).

Or perhaps I've gotten something else wrong.



> b and c both fit in 31 bits

They don't fit into a 31 bit two's complement (i.e. signed) representation, in terms of representing their interpretation as the familiar 32 bit INT_MAX.

31 bit two's complement goes from -0x40000000 to 0x3FFFFFFF. There is a 0x7FFFFFFF bit pattern, which represents -0x00000001. It has a sign bit which is 1. (So, adding that to itself does go to -2, but under that interpretation there is no overflow.)

Any pair of values in that range can be added or subtracted in 32 bit two's complement.

Including the most negative value: -0x40000000 + -0x40000000 = -0x80000000.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: