# C 语言中的位运算

C 语言中的位运算，是用运算符 `~`（按位取反）、`&`（按位与）、`|`（按位或）、`^`（按位异或）、`<<`（左移）和 `>>`（右移）对整数值的各个二进制位进行的计算。正是这类特性，让丹尼斯·里奇（Dennis Ritchie）于 20 世纪 70 年代初在贝尔实验室（Bell Laboratories）为 UNIX 相关工作所创造的 C 语言能够贴近硬件运行。<sup>[1](https://computerhistory.org/profile/dennis-ritchie/)</sup> 标准将它们归为一元运算符 `~` 与二元运算符 `<<`、`>>`、`&`、`^`、`|`，这些运算符都要求操作数为整数类型，并指出其结果取决于整数的内部表示。<sup>[2](https://open-std.org/JTC1/SC22/WG14/issues/c23/issue1067.html)</sup>

| 关键事实 | 详情 |
|---|---|
| 运算符 | `~`、`&`、`|`、`^`、`<<`、`>>`，以及复合赋值 `&=`、`|=`、`^=`、`<<=`、`>>=`<sup>[3](https://cppreference.com/c/language/operator_arithmetic)</sup><sup> • </sup><sup>[4](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/integers-int/int13-c/)</sup> |
| 转换 | `&`、`^`、`|` 对两个操作数执行寻常算术转换；`~` 执行整型提升；移位运算符对每个操作数分别进行整型提升，结果的类型为左操作数提升后的类型<sup>[3](https://cppreference.com/c/language/operator_arithmetic)</sup> |
| 无符号语义 | 对于无符号类型，`~E` 等于结果类型的最大值减去 `E`；`LHS << RHS` 等于 `LHS * 2^RHS` 对“结果类型最大值加一”取模<sup>[3](https://cppreference.com/c/language/operator_arithmetic)</sup> |
| 有符号风险 | 对负的有符号值右移是实现定义的；移位位数为负，或不小于提升后左操作数的宽度，属于未定义行为<sup>[4](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/integers-int/int13-c/)</sup> |
| 编码规则 | CERT INT13-C 与 MISRA C 2004 规则 12.7 要求程序员只对无符号操作数使用位运算符<sup>[4](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/integers-int/int13-c/)</sup><sup> • </sup><sup>[5](https://chenweixiang.github.io/docs/MISRA-C-2004.pdf)</sup> |
| C23 的变化 | C23 要求采用补码表示，消除了在允许反码与原码时出现的实现定义结果<sup>[2](https://open-std.org/JTC1/SC22/WG14/issues/c23/issue1067.html)</sup> |

## 六个运算符

三个二元逻辑运算符逐位比较其操作数。`&` 仅在两个对应位都为 1 时将该结果位置 1；`|` 在任一位为 1 时置 1；`^` 在两位中恰好一位为 1 时置 1。一元 `~` 翻转其操作数的每一位。微软的 C 语言参考给出了一个简洁的例子，取 `short i = 0xAB00`、`short j = 0xABCD`：`i & j` 得到 `0xAB00`，`i | j` 得到 `0xABCD`，`i ^ j` 得到 `0x00CD`。<sup>[6](https://learn.microsoft.com/en-us/cpp/c-language/c-bitwise-operators?view=msvc-160)</sup>

移位运算符在值内部移动二进制位。`lhs << rhs` 向左移动 `rhs` 个位位置，空出的位补零；`lhs >> rhs` 向右移动。对于无符号左操作数，`LHS << RHS` 的值为 `LHS * 2^RHS` 对“结果类型可表示的最大值加一”取模，因此移出的位直接丢弃。对于值为非负的有符号左操作数，若 `LHS * 2^RHS` 在提升后的类型中可表示，结果为 `LHS * 2^RHS`；否则行为未定义。<sup>[3](https://cppreference.com/c/language/operator_arithmetic)</sup> 一份旨在澄清 C 标准中移位措辞的提案陈述了同样的规则：空出的位补零，无符号结果按结果类型的范围回绕，有符号非负左移若溢出则未定义。<sup>[7](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2811.pdf)</sup>

## 运算前的转换

位运算符并不直接作用于操作数的声明类型。运算符 `&`、`^`、`|` 首先执行寻常算术转换，将两个操作数转换为一个共同的实数类型；`~` 对其单个操作数执行整型提升。<sup>[3](https://cppreference.com/c/language/operator_arithmetic)</sup> 移位运算符在二元运算符中较为特殊：整型提升分别对每个操作数单独进行，而不是寻常算术转换，且结果的类型为左操作数提升后的类型。<sup>[3](https://cppreference.com/c/language/operator_arithmetic)</sup>

这一提升步骤有实际后果。诸如 `0x00f0` 这样的 `uint16_t` 掩码在与更宽的值结合之前会被提升为 `int`（或 `unsigned int`），于是 `a | mask`、`a & ~mask` 和 `a & mask` 这类表达式便在提升后的类型中求值；cppreference 的示例将提升后的掩码打印为 `0x000000f0`，并用这三种形式对值 `0x12345678` 置位、清位和选位。<sup>[3](https://cppreference.com/c/language/operator_arithmetic)</sup> 对于提升后的无符号类型，`~E` 等价于结果类型可表示的最大值减去 `E` 的原值，这正是 `a & ~mask` 能准确清除掩码所覆盖的位的原因。<sup>[3](https://cppreference.com/c/language/operator_arithmetic)</sup>

## 掩码、标志与典型用法

位运算符常用于操作位集合与位掩码。<sup>[3](https://cppreference.com/c/language/operator_arithmetic)</sup> 反复出现的模式有：用 `value | mask` 置位，用 `value & ~mask` 清位，用 `value & mask` 测位，用 `value ^ mask` 翻转位。嵌入式 C 编程指南建议，只要一个值表示序列化字段、硬件寄存器布局、协议字、文件格式数据或一组标志，就应使用无符号类型。<sup>[8](https://www.cloudspress.com/bitwise-operators-in-c-a-practical-guide-to-masks-shifts-promotions-and-safe-code/)</sup>

这一技术可从单个字扩展到大型位集合。Linux 内核的 BPF cpumask 接口提供 `bpf_cpumask_and()`、`bpf_cpumask_or()` 和 `bpf_cpumask_xor()` 来组合处理器掩码，其中 `bpf_cpumask_and()` 在结果至少有一位被置位时返回真；内核还针对普通、非原子的位运算更新会产生竞争的情况，为 `unsigned long` 对象提供了 `set_bit`、`clear_bit`、`test_and_set_bit` 等逐位原子操作。<sup>[9](https://kernel.org/doc/html/latest/bpf/cpumasks.html)</sup><sup> • </sup><sup>[10](https://kernel.org/doc/html/v5.10/core-api/atomic_ops.html)</sup>

## 有符号操作数与未定义行为

C 标准长期以来一直警告：位运算符返回的值取决于整数的内部表示，并且对有符号类型存在实现定义和未定义的方面。<sup>[2](https://open-std.org/JTC1/SC22/WG14/issues/c23/issue1067.html)</sup> CERT 建议 INT13-C 明确陈述了规则：位运算符只应与无符号整数操作数一起使用，因为对有符号整数的位运算结果是实现定义的。右移操作既可以实现为传播符号位的算术移位，也可以实现为补零的逻辑移位；若 `E1 >> E2` 中的 `E1` 为有符号类型且值为负，则结果为实现定义。<sup>[4](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/integers-int/int13-c/)</sup>

移位位数本身也有风险。若移位的右操作数为负，或大于等于提升后左操作数的宽度，则行为未定义；CERT 将此单独列为规则 INT34-C。<sup>[4](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/integers-int/int13-c/)</sup><sup> • </sup><sup>[11](https://www.jpcert.or.jp/sc-rules/c-int34-c.html)</sup> JPCERT 指出，在处理器层面，许多架构会将移位位数按类型宽度取模，例如 IA-32 的 `sall` 指令将计数寄存器掩码到其低五位，产生 [0, 31] 范围内的值，这就是为什么尽管 C 语言层面的行为未定义，此类缺陷的风险仍被评为低。<sup>[11](https://www.jpcert.or.jp/sc-rules/c-int34-c.html)</sup>

CERT 的不合规示例展示了有符号移位如何变成安全漏洞：取 `int stringify = 0x80000000`，在传播符号位的实现上，表达式 `stringify >> 24` 求值为 `0xFFFFFF80`，即 4,294,967,168，这个值对接收它的缓冲区来说过大；将 `stringify` 声明为 `unsigned int` 可使结果成为 `stringify / 2^24` 的整数部分，从而消除该风险。<sup>[4](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/integers-int/int13-c/)</sup> CERT 将该规则评为高严重性、优先级 P6，并指出对有符号数执行位运算在某些情况下可能导致缓冲区溢出和任意代码执行。<sup>[4](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/integers-int/int13-c/)</sup>

编码标准将这一建议固化为要求。MISRA C:2004 规则 12.7（必需）禁止对底层类型为有符号的操作数使用位运算符，因为右移可能将符号位推入数值，或左移可能将数值位推入符号位，从而产生困难。<sup>[5](https://chenweixiang.github.io/docs/MISRA-C-2004.pdf)</sup> CERT 给予两项例外：用作位标志的预处理器宏或枚举常量即使未显式声明为无符号，也可传给 `&` 和 `|`；编译期常量的右移位数可以为有符号类型，前提是它为正。<sup>[4](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/integers-int/int13-c/)</sup>

## C23 改变了什么

有符号位运算的实现定义性质可追溯到 C 支持多种负数表示的历史。在 C23 之前，负值的表示可能各不相同，这导致位运算符产生实现定义的结果；而试图生成负零——反码与原码允许、补码不允许——在不支持的情况下会导致未定义行为。C23 要求采用无负零的补码表示，因此这些问题不再可能出现；一项尚未解决的 WG14 议题提议删除现已过时的警告段落，并将附录 J 的可移植性说明收窄到负的有符号整数的右移，包括零的右移。<sup>[2](https://open-std.org/JTC1/SC22/WG14/issues/c23/issue1067.html)</sup> 现行标准 ISO/IEC 9899:2024（第 5 版）于 2024 年 10 月发布。<sup>[12](https://committee.iso.org/standard/82075.html)</sup>

编译器行为仍以有据可查的方式存在差异。微软 C 编译器规定，对有符号整数的位运算与对无符号整数的位运算相同，因此 `-16 & 99` 得到 96。<sup>[6](https://learn.microsoft.com/en-us/cpp/c-language/c-bitwise-operators?view=msvc-160)</sup> GCC 文档指出，位运算符作用于值的表示，包括符号位和数值位，符号位被视为紧邻权值最高的数值位之上。<sup>[4](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/integers-int/int13-c/)</sup>

## References

1. [Dennis Ritchie, Computer History Museum](https://computerhistory.org/profile/dennis-ritchie/)
2. [WG14 Issue 1067: Bitwise operators on signed types](https://open-std.org/JTC1/SC22/WG14/issues/c23/issue1067.html)
3. [Arithmetic operators, cppreference.com (C)](https://cppreference.com/c/language/operator_arithmetic)
4. [INT13-C. Use bitwise operators only on unsigned operands, SEI CERT C Coding Standard](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/integers-int/int13-c/)
5. [MISRA C:2004 Rule 12.7](https://chenweixiang.github.io/docs/MISRA-C-2004.pdf)
6. [C Bitwise Operators, Microsoft Learn](https://learn.microsoft.com/en-us/cpp/c-language/c-bitwise-operators?view=msvc-160)
7. [Proposal for C23, WG14 N2811](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2811.pdf)
8. [Bitwise Operators in C: A Practical Guide to Masks, Shifts, Promotions, and Safe Code](https://www.cloudspress.com/bitwise-operators-in-c-a-practical-guide-to-masks-shifts-promotions-and-safe-code/)
9. [BPF cpumask kfuncs, The Linux Kernel documentation](https://kernel.org/doc/html/latest/bpf/cpumasks.html)
10. [Semantics and Behavior of Atomic and Bitmask Operations, The Linux Kernel documentation](https://kernel.org/doc/html/v5.10/core-api/atomic_ops.html)
11. [INT34-C (Japanese translation), JPCERT](https://www.jpcert.or.jp/sc-rules/c-int34-c.html)
12. [ISO/IEC 9899:2024, ISO](https://committee.iso.org/standard/82075.html)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 17, 2026; Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 物质世界与数学 › 数学与统计学 › 数与代数 › Arithmetic and number systems › Computational arithmetic

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/bitwise-operations-in-c

English original: https://www.edgepedia.org/bitwise-operations-in-c
