0
votes

My doubt is how to deal with the most negative number in two's complement representation. I will describe the problem in 1 byte representation, just to be easy. The most positive number is

01111111

which is 127 in decimal. Its two's complement is easy to calculate. Just reversing the bits we get

10000000

Then add the unit

10000001

which is -127 in decimal. The zero number has the particular behaveour, since it two's complement to itself, which is well know. However I had dificults when I saw that the most negative number also two's complemnt to itself. The most negative is -128 which is 10000000 The complement is 01111111 And if we add the unit we get 10000000 which is of course a wrong result. My question is if this number is never used or if it is never reached

1

1 Answers

0
votes

It is used, but in some sense it is the "strangest number". Sometimes it is chosen not to use it, or to reserve it to indicate error conditions. Those are just conventions that are sometimes used, there is nothing inherently preventing the normal use of the most negative integer. In many cases, a number won't be negated, and then this special property just does not come up.

This strange property of two's complement integers means that in some scenarios where it is customary to take an absolute value and calculate with non-negative numbers, it makes sense to instead take the negative absolute value (which negates positive inputs, rather than negative inputs) and calculate with non-positive numbers. That helps because the normal absolute value has the quirk that the most negative integer has no positive counterpart, but there is no such quirk for positive numbers so they can all be safely negated. This trick is not always applicable.

-128 negating to itself is not always the wrong thing to happen. Despite the seemingly incorrect result, it is still the case (using the standard definition of addition) that x + (-x) = 0 for all values including -128, so it is algebraically sensible. It also interacts at least somewhat reasonably with taking the absolute value: while it is true that abs(x) can yield a negative result this way (which is often undesirable), reinterpreting the result as an unsigned number of the same size makes the result correct, (unsigned 8 bit)abs(-128) = 128.

The most negative integer is relatively frequently used in bit-manipulation code. Its arithmetic properties are less important there, making the number "less strange".