首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 位元運算符完整指南:邏輯運算、移位、補數與實戰技巧

     編輯:關於C#

位元運算符直接操作二進制位,是系統程式設計、效能優化、旗標處理、加密演算法的基石。C# 提供六大位元運算符,支援整數類型與 enum 旗標。

六大運算符速覽

運算符名稱元數說明
&位元 AND二元雙方皆 1 才為 1
|位元 OR二元任一方為 1 即為 1
^位元 XOR二元相異為 1,相同為 0
~位元補數一元逐位翻轉 (0↔1)
<<左移二元高位捨棄,低位補 0
>>右移二元視符號/類型決定高位填充

核心運算規則與範例

1. 位元 AND (&) — 遮罩/檢測旗標

// 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. 位元 OR (|) — 設定旗標/合併

// 2 (0010) | 10 (1010) = 10 (1010)
Console.WriteLine(2 | 10); // 10

// 實戰:授予權限
userPerm |= Permissions.Write; // 現在擁有 Read|Write|Execute (7)

3. 位元 XOR (^) — 切換/比較差異

// 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; // 還原

4. 位元補數 (~) — 翻轉所有位

// 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位無號)

5. 左移 (<<) — 乘 2 的冪次

10 << 1  // 20 (10100)
10 << 2  // 40 (101000)

// 實戰:快速乘法、建立遮罩
int mask = 1 << 3; // 0b1000 = 8 (第 3 位)

6. 右移 (>>) — 除 2 的冪次(算術/邏輯位移)

類型行為範例
有號 (int, long)算術右移:保持符號位 (負數高位補 1)-16 >> 2 = -4
無號 (uint, ulong)邏輯右移:高位補 04294967280u >> 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 最佳實踐

[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 (有號)

效能考量

  • 單指令對應 (AND, OR, XOR, NOT, SHL, SHR)
  • 避免在熱路徑使用 BigInteger 位元運算
  • BitOperations 類別 (.NET Core 3.0+) 提供硬體加速操作:PopCount, LeadingZeroCount, RotateLeft

精通位元運算能解鎖高效能演算法、緊湊資料結構與底層硬體互動,是進階 C# 開發者的必修課。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved