Logical Functions, Sign Extensions, and Overflow
--
As discussed here, bits are essential building blocks for information and data. The value of a bit comes from the electrical pulses: the voltage, received by the bit. We use a standard known as 2’s Complement to write binary such that addition and subtraction work. In the last segment, we showcased an edge-case where addition would fail: overflow.
Overflow occurs when the most significant bit is incremented beyond the range of bits. For example, 0111 + 0001 = 7 + 1 should equal 8; however, this equals 1000, which is -8 in 2’s Complement, as the Most Significant Bit is used to represent whether the value is positive or negative. How do we cope with such an issue?
We will have to put fail-safes in our system to check whether or not two negatives form a positive or two positives form a negative, which we know can never happen. Keeping track of that kind of information is beyond the scope of what we are learning about today; so, now, we will focus our attention on how to utilize overflow, in particular, length overflow.
Sign-Extension:
When we add values in decimal, for example: 100 + 10, what we are implicitly doing is appending a 0 in front of the 10 such that the values will match: 100 + 010 = 110. Can we do this same thing with binary addition? How would that work?
Let’s take an example with two numbers, the first one consisting of 8 bits — a byte:
00001110 = 14
+ 1101 = -3
What do we do in this circumstance? Do we just put 0s out in front of the -3? After all, that is what we’ve done with the decimal addition. Let’s try it and find out!
00001110 = 14
+00001101 = 13
=00011011 = 27
Well, that didn’t work.
Instead, let’s try to extend the value of the most-significant bit. That way, a negative will remain a negative and a positive will remain a positive.
00001110 = 14
11111101 = -3
00001011 = 11
Notice how we are using length overflow in our favor. This creates what is known as a carry-out bit. We are letting the most significant bit trail off when it goes out of bounds of what our bytes can store; thus, a negative — that has an absolute value less than the positive number to which it is being added — does…