第 47 / 187 篇

4.4. 二进制整数运算

说明

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

4.4. Binary Integer Arithmetic

介绍了无符号整数和有符号整数的二进制表示之后,我们就可以在算术运算中使用它们了。幸运的是,由于它们的编码方式,无论我们把操作数或结果解释为有符号还是无符号,对算术运算过程来说都没有区别。这对硬件设计者来说是个好消息,因为这让他们可以构建一套硬件部件,同时用于无符号和有符号运算。硬件一章会更详细地介绍执行算术运算的电路。

Having presented binary representations for unsigned and signed integers, we’re ready to use them in arithmetic operations. Fortunately, due to their encoding, it does not matter to the arithmetic procedures whether we choose to interpret the operands or result as signed or unsigned. This observation is great news for hardware designers because it allows them to build one set of hardware components that can be shared for both unsigned and signed operations. The hardware chapter describes the circuitry for performing arithmetic in more detail.

幸运的是,你在小学学过的用纸笔对十进制数做算术的算法,同样适用于二进制数。尽管硬件计算它们的方式可能不完全相同,但你至少应该能看懂这些计算。

Luckily, the same pencil-and-paper algorithms you learned in grade school for performing arithmetic on decimal numbers also work for binary numbers. Though the hardware might not compute them in exactly the same way, you should at least be able to make sense of the calculations.