Hacker News new | ask | show | jobs
by 6a74 1380 days ago
Neat quiz. Reminds me that the absolute value of INT_MIN in C (and many other languages) is undefined, but will generally still return a negative value. This is a "gotcha" that a lot of people are unaware of.

> abs(-2147483648) = -2147483648

2 comments

A consequence of most, if not all, CPUs today using two's complement integers.

I think one's complement is more sensible since it doesn't have this problem, but it loses out because it requires a more complex ISA and implementation.

It's annoying that negation, ABS, and division can overflow with two's complement. But how I look at it: lots of operations can already overflow, just a fact of signed integers, and you need to guard against that overflow in portable code already. It doesn't seem to be fundamentally worse that those extra operations can overflow.
Ones' complement (correct spelling) has negative zero, which I would argue is a far worse problem.
Why in the fuck is it “ones' complement”, but “two's complement”?
According to Wikipedia:

> The name "ones' complement" (note this is possessive of the plural "ones", not of a singular "one") refers to the fact that such an inverted value, if added to the original, would always produce an 'all ones' number

And two's complement refers to what?
The radix complement in base two. They are closely related but not identical - the two's complement representation of a negative number is the ones' complement representation + 1 (ignoring the final carry). In ones' complment there are two representations for 0 (all 0s or all 1s), but every number has a positive and negative representation. In two's complement, there is a single 0, but there is also negative number that doesn't have a corresponding positive representation (INT_MIN).

In fact, for every numerical base there is an equivalent. For example, in base 3 you can represent a number in twos' complement notation (each trit X is replaced with 2-X, so -3 is represented as 212 on three trits, with +3 being 010) is or in three's complement by adding 1 (212+1 = 220). For base 10, you can do nines' complement (-3 on 3 digits is 996) or ten's complement (996+1 = 997).

It is undefined since it involves integer overflow