> 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/bitwise.md).

# 位运算

### 六种位运算

| 运算   | 符号   | 说明                |
| ---- | ---- | ----------------- |
| 按位与  | `&`  | 同 1 才为 1          |
| 按位或  | `\|` | 有 1 则为 1          |
| 按位非  | `~`  | 0 变 1、1 变 0（含符号位） |
| 按位异或 | `^`  | 相同为 0，不同为 1       |
| 左移   | `<<` | 整体左移，低位补 0，相当于乘 2 |
| 右移   | `>>` | 整体右移，相当于整除 2      |

### 运算示例（以 8 位为例）

```
5 = 0000 0101
3 = 0000 0011
5 & 3 = 0000 0001 = 1
5 | 3 = 0000 0111 = 7
5 ^ 3 = 0000 0110 = 6
5 << 1 = 0000 1010 = 10
5 >> 1 = 0000 0010 = 2
```

### 技巧

* `x & 1` 判断奇偶：为 1 是奇数，为 0 是偶数
* `x << 1` 等价于 `x * 2`，`x >> 1` 等价于 `x / 2`
* 异或交换两数（不需要临时变量）：`a ^= b; b ^= a; a ^= b;`
* `x ^ x = 0`，`x ^ 0 = x`

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

int main() {
    int a = 5, b = 3;
    cout << (a & b) << endl;  // 1
    cout << (a | b) << endl;  // 7
    cout << (a ^ b) << endl;  // 6
    cout << (a << 1) << endl; // 10
    return 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/bitwise.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.
