第 49 / 187 篇

4.4.2. 减法

说明

本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C4-Binary/arithmetic_subtraction.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。

4.4.2. Subtraction

减法结合了两种熟悉的运算:取负和加法。换句话说,计算 7 - 3 等价于把这个运算表示成 7 + (-3)。这样描述减法与硬件的行为很吻合——CPU 本来就含有取负电路和加法电路,所以复用这些电路,要比另造一个全新的减法器合理。回想一下,对二进制数取负的一个简单方法是翻转各位再加一。

Subtraction combines two familiar operations: negation and addition. In other words, subtracting 7 - 3 is equivalent to expressing the operation as 7 + (-3). This portrayal of subtraction aligns well with how the hardware behaves — a CPU already contains circuits for negation and addition, so it makes sense to reuse those circuits rather than build an entirely new subtractor. Recall that a simple procedure to negate a binary number is to flip the bits and add one.

来看 0b0111(7)- 0b0011(3)这个例子,它先把 3 送进一个翻转各位的电路。为了得到「加一」,它利用了加法器电路的进位输入。也就是说,减法不是从一位向另一位进位,而是向加法器的 d0 送入一个进位输入。把进位输入设为 1,会使结果的「个位」值加一,这正是取负中「加一」那部分所需要的。综合起来,这个例子如下:

Consider the example 0b0111 (7) - 0b0011 (3), which starts by sending the 3 to a bit-flipping circuit. To get the “plus one,” it takes advantage of the carry in to the adder circuit. That is, rather than carrying from one digit to another, subtraction feeds a carry in to d0 of the adder. Setting the carry in to 1 increases the resulting “ones place” value by one, which is exactly what it needs to get the “plus one” part of the negation. Putting it all together, the example would look like the following:

题目

Problem Setup

1
2
3
 
0111
- 0011

转换为加法

Converted to Addition

1
2
3
     1 (carry in)
0111
+ 1100 (bits flipped)

计算过程

Worked Example

1
2
3
4
5
6
                1 (carry in)
0111
+ 1100 (bits flipped)

Result: 0100
Carry out: 1

虽然完整的加法结果向多出来的一位进了位,但截断后的结果(0b0100)表示的正是预期的结果(4)。与前面加法的例子不同,对减法来说,从高位进位输出并不一定意味着溢出问题。

While the full result of the addition carries into an extra digit, the truncated result (0b0100) represents the expected result (4). Unlike the previous addition example, a carry out from the high-order bit is not necessarily indicative of an overflow problem for subtraction.

把减法当作先取负再相加来执行,在减去一个负值时同样有效。例如,7 - (-3) 得到 10:

Performing subtraction as negation followed by addition also works when subtracting a negative value. For example, 7 - (-3) produces 10:

题目

Problem Setup

1
2
3
 
0111
- 1101

转换为加法

Converted to Addition

1
2
3
     1 (carry in)
0111
+ 0010 (bits flipped)

计算过程

Worked Example

1
2
3
4
5
6
                1 (carry in)
0111
+ 0010 (bits flipped)

Result: 1010
Carry out: 0

我们会在溢出一节中进一步探讨有没有进位输出意味着什么。

We further explore the implications of carrying out (or not) in the overflow section.