位元運算符直接操作二進制位,是系統程式設計、效能優化、旗標處理、加密演算法的基石。C# 提供六大位元運算符,支援整數類型與 enum 旗標。
| 運算符 | 名稱 | 元數 | 說明 |
|---|---|---|---|
& | 位元 AND | 二元 | 雙方皆 1 才為 1 |
| | 位元 OR | 二元 | 任一方為 1 即為 1 |
^ | 位元 XOR | 二元 | 相異為 1,相同為 0 |
~ | 位元補數 | 一元 | 逐位翻轉 (0↔1) |
<< | 左移 | 二元 | 高位捨棄,低位補 0 |
>> | 右移 | 二元 | 視符號/類型決定高位填充 |
&) — 遮罩/檢測旗標// 2 (0010) & 10 (1010) = 2 (0010)
Console.WriteLine(2 & 10); // 2
// 實戰:檢測旗標
[Flags] enum Permissions { Read = 1, Write = 2, Execute = 4 }
var userPerm = Permissions.Read | Permissions.Execute; // 5 (0101)
bool canWrite = (userPerm & Permissions.Write) != 0; // false
|) — 設定旗標/合併// 2 (0010) | 10 (1010) = 10 (1010) Console.WriteLine(2 | 10); // 10 // 實戰:授予權限 userPerm |= Permissions.Write; // 現在擁有 Read|Write|Execute (7)
^) — 切換/比較差異// 2 (0010) ^ 10 (1010) = 8 (1000) Console.WriteLine(2 ^ 10); // 8 // 實戰:切換旗標 userPerm ^= Permissions.Execute; // 移除 Execute // 加密:簡單 XOR 加密 byte key = 0xAA; byte encrypted = data ^ key; byte decrypted = encrypted ^ key; // 還原
~) — 翻轉所有位// 10 (00001010) → ~10 = 11110101 // 有號整數:補數表示法 → -11 // 無號整數:視位寬決定值 Console.WriteLine(~10); // -11 (int) Console.WriteLine((uint)~10); // 4294967285
關鍵點:結果值取決於運算元類型位寬與符號性:
short a = 10; Console.WriteLine(~a); // -11 (16位) ushort b = 10; Console.WriteLine(~b); // 65525 (16位無號) int c = 10; Console.WriteLine(~c); // -11 (32位) uint d = 10; Console.WriteLine(~d); // 4294967285 (32位無號)
<<) — 乘 2 的冪次10 << 1 // 20 (10100) 10 << 2 // 40 (101000) // 實戰:快速乘法、建立遮罩 int mask = 1 << 3; // 0b1000 = 8 (第 3 位)
>>) — 除 2 的冪次(算術/邏輯位移)| 類型 | 行為 | 範例 |
|---|---|---|
| 有號 (int, long) | 算術右移:保持符號位 (負數高位補 1) | -16 >> 2 = -4 |
| 無號 (uint, ulong) | 邏輯右移:高位補 0 | 4294967280u >> 2 = 1073741820 |
int x = 16; Console.WriteLine(x >> 2); // 4 Console.WriteLine(x >> 4); // 1 Console.WriteLine(x >> 6); // 0 int neg = -16; Console.WriteLine(neg >> 2); // -4 (11111100) Console.WriteLine(neg >> 4); // -1 (11111111) — 飽和於 -1
[Flags]
enum FileAccess : uint
{
None = 0,
Read = 1 << 0, // 1
Write = 1 << 1, // 2
Execute = 1 << 2, // 4
Delete = 1 << 3, // 8
All = Read | Write | Execute | Delete // 15
}
// 使用
var access = FileAccess.Read | FileAccess.Write;
access |= FileAccess.Execute;
access &= ~FileAccess.Write; // 移除 Write
bool canRead = access.HasFlag(FileAccess.Read);
// 判斷 2 的冪次
bool IsPowerOfTwo(int n) => n > 0 && (n & (n - 1)) == 0;
// 取模 2^n (n 為正整數)
int ModPowerOfTwo(int x, int n) => x & ((1 << n) - 1);
// 交換兩數 (無需暫存)
a ^= b; b ^= a; a ^= b;
// 取絕對值 (無分支)
int Abs(int x) => (x ^ (x >> 31)) - (x >> 31);
// 計算設定位數 (Population Count)
int PopCount(uint x) {
x -= (x >> 1) & 0x55555555;
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
return (int)((x * 0x01010101) >> 24);
}
checked 區塊)count & 0x1F (int) 或 count & 0x3F (long)x * 2 → x << 1,x / 2 → x >> 1 (有號)BigInteger 位元運算BitOperations 類別 (.NET Core 3.0+) 提供硬體加速操作:PopCount, LeadingZeroCount, RotateLeft精通位元運算能解鎖高效能演算法、緊湊資料結構與底層硬體互動,是進階 C# 開發者的必修課。