Integer Representation
Two’s complement representation
Conversion
- For positive numbers (+)
- complement ← original (补码=原码)
- original ← complement (原码=补码)
- For negative numbers (-)
- complement = reversed(abs(original)) + 1 (补码=正数的反码+1)
- original ← -reverse(complement-1) (原码= 补码-1,反转,再加负号)
- All binary (addition/subtraction) calculations are done directly with complements (in a computer)
Purpose
- 统一加减法:减法可以转换为加法来处理。
- 简化溢出处理:正负数的溢出方式相同,简化了溢出的检测和处理逻辑。
- 避免两个零:假若不用补码,则$0000_2$, $1000_2$ 都代表0.
- 简化电路:通过将正负数都转换为补码,计算机可以使用原本为无符号数设计的电路来处理有符号数。这降低了硬件设计的复杂性。
<aside>
💡 因此:电脑并不会区分符号;同一个二进制可以表示不同的数据,由人定义
- E.g., 8位的无符号整数
0xFF,在补码表示中也可看作是有符号整数1。
- 但这种兼容性靠程序员的明确处理,因为计算机不会自动区分这两种情况。
</aside>
ALU Overflow Detection
- if two numbers are added,
- and they are both positive or both negative,
- then overflow occurs if and only if the result has the opposite signs
Addition & Subtraction
- For addition: convert any negative numbers to two’s complement and bitwise addition
- For subtraction: convert to addition (e.g., $a-b\to a+(-b)$)
Multiplication