> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/computer-basics/binary-encoding.md).

# 数据编码（原码、反码、补码）

### 三种编码

计算机中整数用**补码**存储。以 8 位为例：

| 编码 | 正数         | 负数          |
| -- | ---------- | ----------- |
| 原码 | 符号位 0 + 数值 | 符号位 1 + 数值  |
| 反码 | 与原码相同      | 符号位不变，数值位取反 |
| 补码 | 与原码相同      | 反码 + 1      |

### 举例：+5 与 -5（8 位）

```
+5 原码/反码/补码：0000 0101
-5 原码：1000 0101
-5 反码：1111 1010
-5 补码：1111 1011
```

### 为什么要用补码

* 把减法变成加法：`a - b = a + (-b) 的补码`
* 0 只有一种表示，避免 +0 和 -0 的歧义
* 表示范围：8 位补码为 `-128 ~ 127`

### 溢出的直观理解

```cpp
#include <iostream>
using namespace std;

int main() {
    int x = 2147483647;   // int 最大值
    cout << x + 1 << endl; // 溢出，变为 -2147483648
    return 0;
}
```

> 注意区分：`unsigned int` 没有符号位，范围是 `0 ~ 4294967295`，溢出后从 0 重新开始。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/computer-basics/binary-encoding.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
