6 ms·
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
by 6a74 4y 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
- lizardactivist 4y agoA 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.
- veltas 4y agoIt'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.
- deleted 4y ago[deleted]
- nayuki 4y agoOnes' complement (correct spelling) has negative zero, which I would argue is a far worse problem.
- xigoi 4y agoWhy in the fuck is it “ones' complement”, but “two's complement”?
- tsimionescu 4y agoAccording 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
- xigoi 4y agoAnd two's complement refers to what?
- tsimionescu 4y agoThe 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).
- shultays 4y agoIt is undefined since it involves integer overflow