# 3.1 二进制加法

逻辑门可以用来作为电路的控制单元，例如上文中提到的卧室开关，那么我们能将其作为计算单元吗？

由于布尔代数只能表示两种状态，我们考虑用逻辑门来完成二进制的算术运算的可能性。而加法是算术运算的基础，所以我们先考虑二进制加法。二进制的加法与十进制一样，都可以从右至左逐位进行，如果相加的结果大于等于2，则向高位进位，参考下例：

```
 10011
 11001
---------
101100
```

我们先考虑最简单的场景，即两个一位数的加法，情况如下：

| A | B | Sum Bit | Carry Bit |
| - | - | ------- | --------- |
| 0 | 0 | 0       | 0         |
| 0 | 1 | 1       | 0         |
| 1 | 0 | 1       | 0         |
| 1 | 1 | 0       | 1         |

查看结果位（Sum Bit）与进位（Carry Bit）的情况，可以发现结果位相当于 **A XOR B**, 而进位相当于 **A AND B**. 这个结果非常重要，这意味着我们可以基于逻辑运算来构建算术运算。此处我们可以通过一个与门和异或门构建一个能够完成一位二进制加法的电路组件，其构建方式如下：

![Half Adder](/files/-MdWGbfd4Y_G73u_IULF)

该电子组件叫着半加器（Half Adder），它只接收两个输入。而在多位的加法运算中，由于可能存在进位，因此每一位相当于在做三位的加法运算。如果我们将进位展现出来的话，上述加法等式表示如下：

```
 10011
 11001
100110 Carry Bit
----------------
101100
```

为了展示方便，我们将最低位的进位设置为0. 只通过半加器无法构建出多位的加法器，因为半加器只接收两个输入而无法接收和处理由低位产生的进位，能够接收进位的加法器叫着全加器（Full Adder），下图是全加器的一种电路设计：

![Full Adder](/files/-MdWH5rLwtLYcmWZwEyT)

有了全加器，就可以组装出任意位数的加法器了，例如下图是一个4位的加法器：

![4 Bit Adder](/files/-MdWHGOaPrQbORpo25Ix)

该加法器能够完成4位的二进制加法运算：

```
   B3 B2 B1 B0
   A3 A2 A1 A0
--------------
C4 S3 S2 S1 S0
```

> &#x20;在现实系统中，由于存储空间始终是有限的，所以最高位通常会被丢弃，这种情况叫着溢出（Overflow）。溢出会导致系统的计算结果不正确，但这是系统需要处理的一种现实情况。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://s2.shizhz.me/s2e3/1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
