1.剖析異或運算(^)
二元 ^ 運算符是為整型和 bool 類型預定義的。對于整型,^ 將計算操作數的按位“異或”。對于 bool 操作數,^ 將計算操作數的邏輯“異或”;也就是說,當且僅當只有一個操作數為 true 時,結果才為 true。
數值運算舉例
按位異或的3個特點:
(1) 0^0=0,0^1=1 0異或任何數=任何數
(2) 1^0=1,1^1=0 1異或任何數-任何數取反
(3) 1^1=0,0^0=0 任何數異或自己=把自己置0
例如:10100001^00010001=10110000
按位異或的幾個常見用途:
(1) 使某些特定的位翻轉
例如對數10100001的第2位和第3位翻轉,則可以將該數與00000110進行按位異或運算。
0100001^00000110 = 10100111
(2) 實現兩個值的交換,而不必使用臨時變量。
例如交換兩個整數a=10100001,b=00000110的值,可通過下列語句實現:
a = a^b; //a=10100111
b = b^a; //b=10100001
a = a^b; //a=00000110
(3) 在匯編語言中經常用于將變量置零:
xor a,a
(4) 快速判斷兩個值是否相等
舉例1: 判斷兩個整數a,b是否相等,則可通過下列語句實現:
return ((a ^ b) == 0)
舉例2: Linux中最初的ipv6_addr_equal()函數的實現如下:
static inline int ipv6_addr_equal(const struct in6_addr *a1, const struct in6_addr *a2)
{
return (a1->s6_addr32[0] == a2->s6_addr32[0] &&
a1->s6_addr32[1] == a2->s6_addr32[1] &&
a1->s6_addr32[2] == a2->s6_addr32[2] &&
a1->s6_addr32[3] == a2->s6_addr32[3]);
}
可以利用按位異或實現快速比較, 最新的實現已經修改為:
static inline int ipv6_addr_equal(const struct in6_addr *a1, const struct in6_addr *a2)
{
return (((a1->s6_addr32[0] ^ a2->s6_addr32[0]) |
(a1->s6_addr32[1] ^ a2->s6_addr32[1]) |
(a1->s6_addr32[2] ^ a2->s6_addr32[2]) |
(a1->s6_addr32[3] ^ a2->s6_addr32[3])) == 0);
}
2 & 運算符(與)1 & 0 為0
0 & 0 為0
1 & 1 為1
3 | 運算符(或)
1 & 0 為1
0 & 0 為0
1 & 1 為1
------------------
C#移位運算(左移和右移)
C#是用<<(左移) 和 >>(右移) 運算符是用來執行移位運算。
左移 (<<)
將第一個操作數向左移動第二個操作數指定的位數,空出的位置補0。
左移相當于乘. 左移一位相當于乘2;左移兩位相當于乘4;左移三位相當于乘8。
x<<1= x*2
x<<2= x*4
x<<3= x*8
x<<4= x*16
同理, 右移即相反:
右移 (>>)
將第一個操作數向右移動第二個操作數所指定的位數,空出的位置補0。
右移相當于整除. 右移一位相當于除以2;右移兩位相當于除以4;右移三位相當于除以8。
x>>1= x/2
x>>2= x/4
x>>3= x/8
x>>4=x/16
如
int i = 7;
int j = 2;
Console.WriteLine(i >> j); //輸出結果為1
當聲明重載C#移位運算符時,第一個操作數的類型必須總是包含運算符聲明的類或結構,并且第二個操作數的類型必須總是 int,如:
class Program
{
static void Main(string[] args)
{
ShiftClass shift1 = new ShiftClass(5, 10);
ShiftClass shift2 = shift1 << 2;
ShiftClass shift3 = shift1 >> 2;
Console.WriteLine("{0} << 2 結果是:{1}", shift1.valA, shift2.valA);
Console.WriteLine("{0} << 2 結果是:{1}", shift1.valB,shift2.valB);
Console.WriteLine("{0} >> 2 結果是:{1}", shift1.valA, shift3.valA);
Console.WriteLine("{0} >> 2 結果是:{1}", shift1.valB, shift3.valB);
Console.ReadLine();
}
public class ShiftClass
{
public int valA;
public int valB;
public ShiftClass(int valA, int valB)
{
this.valA = valA;
this.valB = valB;
}
public static ShiftClass operator <<(ShiftClass shift, int count)
{
int a = shift.valA << count;
int b = shift.valB << count;
return new ShiftClass(a, b);
}
public static ShiftClass operator >>(ShiftClass shift, int count)
{
int a = shift.valA >> count;
int b = shift.valB >> count;
return new ShiftClass(a, b);
}
}
}
因為位移比乘除速度快.對效率要求高,而且滿足2的冪次方的乘除運方,可以采用位移的方式進行。