说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C4-Binary/arithmetic_mult_div.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
4.4.3. Multiplication and Division
本节简要介绍整数的二进制乘法和除法。具体来说,它展示的是手工计算结果的方法,并不反映现代硬件的行为。这里的介绍并不全面,因为本章其余部分主要关注加法和减法。
This section briefly describes binary multiplication and division with integers. In particular, it shows methods for computing results by hand and does not reflect the behavior of modern hardware. This description is not meant to be comprehensive, as the remainder of the chapter focuses primarily on addition and subtraction.
乘法
Multiplication
做二进制乘法时,使用常见的纸笔计算策略:一次考虑一位数字,再把各个结果相加。例如,0b0101(5)乘以 0b0011(3),等价于把以下两项相加:
To multiply binary numbers, use the common pencil-and-paper strategy of considering one digit at a time and adding the results. For example, multiplying 0b0101 (5) and 0b0011 (3) is equivalent to summing:
- d0 乘以 0b101(5)的结果:0b0101(5)
- the result of multiplying d0 by 0b101 (5): 0b0101 (5)
- d1 乘以 0b101(5)、再把结果左移一位的结果:0b1010(10)。
- the result of multiplying d1 by 0b101 (5) and shifting the result to the left by one digit: 0b1010 (10).
1 | 0101 0101 0101 |
(整数)除法
(Integer) Division
与刚才介绍的其他运算不同,除法有可能产生非整数的结果。做整数除法时要记住的主要一点是:在大多数语言(例如 C、Python 2 和 Java)中,结果的小数部分会被截断。除此之外,二进制除法使用的是大多数学生在小学学过的长除法。例如,下面是计算 11 / 3 得到整数结果 3 的过程:
Unlike the other operations just described, division has the potential to produce a non-integral result. The primary thing to keep in mind when dividing integers is that in most languages (for example, C, Python 2, and Java) the fractional portion of the result gets truncated. Otherwise, binary division uses the same long form method that most students learn in grade school. For example, here’s how computing 11 / 3 produces an integer result of 3:
译注
两点补充:① Python 3 中 / 是真除法(11 / 3 得 3.666...),整数除法要用 //,而且 // 是向负无穷取整(-7 // 2 得 -4);② C(自 C99 起)的整数除法是向零截断(-7 / 2 得 -3,-7 % 2 得 -1)。处理负数时这两种语言的结果不同。
1 | ____ |
到这里,算术运算得出了预期的整数结果 0011(3),硬件会截断任何小数部分。如果你想求出整数余数,可以使用取模运算符(%),例如 11 % 3 = 2。
At this point, the arithmetic has produced the expected integer result, 0011 (3), and the hardware truncates any fractional parts. If you’re interested in determining the integral remainder, use the modulus operator (%); for example, 11 % 3 = 2.