Before you read this section, make sure you are comfortable with adders. Subtraction, after all, can be modeled as addition. Observe that, 5 - 2 is equivalent to 5 + (-2).
We would need an extra bit of information to convey parity. So, 0 for positive and 1 for negative.
Ok great, now what? Say we use three bits of information and one leading bit for parity:
0101
is 5 and 1010
represents -2. Using a regular adder would yield
1111
. Hm, not quite right.
Observe that although -2 represented as 1010
does not yield the right result, adding
16 to this representation (so adding 14 instead) does, and this produces an overflow carry we disregard:
0101 1110 ---- 10011
The two values are synonymous due to modular arithmetic, where we take 2^(number of bits) - (value)
to be added instead. So for -2, this could be 14, 30, 46,…, etc., but we choose 14 since we can only represent
that given our number of bits.
16 = 2 (mod 14)
Think about modular arithmetic like a clock; -2 can be thought of as -2 o'clock or 10 o'clock. 10 o'clock is
more useful for us. This is called two's complement. We can flip all the bits and add 1
(15 - X + 1
), which is equivalent to (16 - X)
or the modulus. Note that this can be
extended to 5 bits (32) and so forth.
So 2 is 0010
, but if we do 15 - 2
, (or observe that this operation flips all bits),
we get 1101
. If we add 1, we get 1110
, which is what we listed above. Going from a negative digit to a positive digit entails the same process.
In Minecraft, all you would need to do is negate your inputs and add one to an input.