1. 導入
C語言的位元運算概述
C語言為了有效率地操作記憶體與處理器,提供了位元運算功能。其中最重要的就是「XOR(異或運算)」。
位元運算常被應用於資料加密、資料驗證、數值操作等多種場景。XOR的特點是,當兩個位元不同時回傳「1」,相同時回傳「0」,因此是一種簡單且強大的運算方式。
本文將依序說明C語言中XOR運算的基礎到應用,並搭配實際程式碼範例,讓初學者也能輕鬆理解。
2. XOR運算子的基礎
什麼是XOR?
XOR(異或運算)是將兩個數值的每一位元逐一比較,只有在該位元不同時才回傳「1」,相同時則為「0」。例如,下方以數字5與9進行位元比較,得到XOR運算的結果:
- 5 的二進位:
0101
- 9 的二進位:
1001
將這些位元進行XOR運算比較如下:
位元位置 | 5 (0101) | 9 (1001) | XOR結果 |
---|---|---|---|
1 | 0 | 1 | 1 |
2 | 1 | 0 | 1 |
3 | 0 | 0 | 0 |
4 | 1 | 1 | 0 |
結果為 1100
,也就是十進位的「12」。只要理解XOR的基本運作,就能應用在更複雜的位元運算中。
3. 透過範例程式碼理解XOR
基本XOR使用範例
下方是C語言執行XOR運算的簡單範例,對數字5與9進行XOR並顯示結果:
#include <stdio.h>
int main() {
int a = 5;
int b = 9;
int result = a ^ b;
printf("5 XOR 9 = %dn", result); // 結果是12
return 0;
}
這段程式會計算 a
與 b
的位元XOR運算並存到 result
。執行結果顯示「5 XOR 9 = 12」,非常適合用來理解位元運算。
4. XOR的應用範例
使用XOR交換變數值
善用XOR的特性,兩個變數可以不使用暫存變數就直接交換。以下程式碼示範用XOR交換 a
與 b
的值:
#include <stdio.h>
int main() {
int a = 5;
int b = 7;
printf("交換前: a = %d, b = %dn", a, b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("交換後: a = %d, b = %dn", a, b);
return 0;
}
這段程式透過三次XOR,就能有效交換 a
和 b
的值,不需暫存變數,也能節省記憶體。

5. 實務範例與應用範圍
檢測陣列中重複數字或出現奇數次的數字
XOR還能用於高效檢查陣列中的重複元素或出現奇數次的元素。以下提供檢查重複元素和找出奇數次元素的範例:
找出重複數字
#include <stdio.h>
int findDuplicate(int nums[], int size) {
int duplicate = 0;
for (int i = 0; i < size; i++) {
duplicate ^= nums[i];
}
return duplicate;
}
int main() {
int nums[] = {1, 2, 3, 2, 4};
int size = sizeof(nums) / sizeof(nums[0]);
printf("Duplicate number is: %dn", findDuplicate(nums, size));
return 0;
}
這段程式利用XOR的特性檢查陣列中重複的數字。只要相同數字XOR兩次會歸零,因此只剩下重複的數字。
找出出現奇數次的數字
#include <stdio.h>
int findOddOccurrence(int nums[], int size) {
int result = 0;
for (int i = 0; i < size; i++) {
result ^= nums[i];
}
return result;
}
int main() {
int nums[] = {5, 3, 9, 3, 5, 9, 7};
int size = sizeof(nums) / sizeof(nums[0]);
printf("Odd occurring number is: %dn", findOddOccurrence(nums, size));
return 0;
}
這段程式可快速找出出現奇數次的數字,因為只有這個數字最後會保留在XOR結果中。
XOR在資料加密中的應用
XOR也常被應用於資料加密。下方範例是利用XOR進行簡單加解密的程式:
#include <stdio.h>
void encryptDecrypt(char data[], char key) {
for (int i = 0; data[i] != ' '; i++) {
data[i] = data[i] ^ key;
}
}
int main() {
char data[] = "Hello World";
char key = 'K';
printf("原始資料: %sn", data);
encryptDecrypt(data, key);
printf("加密後: %sn", data);
encryptDecrypt(data, key);
printf("解密後: %sn", data);
return 0;
}
這段程式對資料使用XOR進行加密,再次使用XOR則可還原原本的資料,因此常作為簡易的加解密技術。
6. 結論
本文說明了C語言中XOR運算的基礎與各種應用範例。XOR廣泛用於資料加密、錯誤檢查、程式最佳化、雜湊函式設計等多種領域。特別是其高速與高效率,讓它在大規模資料處理或追求效能的情境下扮演重要角色。
希望透過本文,讓您理解XOR運算的強大之處,並能應用於未來的程式開發中。