> 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/data-structures/gray-code.md).

# 格雷编码

### 定义

格雷编码是一种相邻两个数**只有一位不同**的编码方式，常用于减少数字电路切换错误。

### 二进制与格雷码的转换

* **二进制转格雷码**：`g = b ^ (b >> 1)`
* **格雷码转二进制**：最高位相同，其后每位等于前一位二进制与当前格雷码位的异或

```cpp
// 二进制 n 转格雷码
int toGray(int n) { return n ^ (n >> 1); }

// 格雷码 g 转二进制
int toBinary(int g) {
    int b = g;
    while (g >>= 1) b ^= g;
    return b;
}
```

### 3 位格雷码

```
000, 001, 011, 010, 110, 111, 101, 100
```

相邻两数（含首尾）都只差一位，故格雷码也是一种“循环码”。

### 性质

n 位格雷码共有 `2^n` 个码字，其中第 i 个格雷码就是 `i ^ (i >> 1)`。


---

# 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/data-structures/gray-code.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.
