| Integers: 2's complement | ||||||||||||
| 2's complement (2C) may not be intuitively obvious, but it has nice properties | ||||||||||||
| Negation | ||||||||||||
| 1. flip all bits | ||||||||||||
| 2. add 1 (ignoring any carry out of the msb) | ||||||||||||
| Example: 11ten is 01011 in 5-bit unsigned binary. Call this number B. | ||||||||||||
| 1. flip bits: | 10100 | ~B | ||||||||||
| 2. add 1: | + 1 | |||||||||||
| 10101 | -B | |||||||||||
| What do we get if we add this to the original number? | ||||||||||||
| 01011 | B | |||||||||||
| + | 10101 | + -B | ||||||||||
| 00000 | 0 | |||||||||||
| If we negate B (-B) using 2C and negate again (--B) we get the original value B back. | ||||||||||||
| 1. flip bits: | 01010 | ~(-B) | ||||||||||
| 2. add 1: | + 1 | |||||||||||
| 01011 | B | |||||||||||
| Other ways to do N-bit 2C negation: | ||||||||||||
| 1. Find the rightmost 1 bit, then flip all the higher bits (bits to the left). | ||||||||||||
| Example: | 01011 | |||||||||||
| Rightmost 1 bit is b0 | ||||||||||||
| flip bits to the left: | 10101 | |||||||||||