参与运算的两个值,如果两个相应位相同,则结果为0,否则为1。即:0^0=0, 1^0=1, 0^1=1, 1^1=0
异或运算符的特点是:数a两次异或同一个数b(a=a^b^b)仍然为原值a.通过按位异或运算,可以实现两个值的交换,而不必使用临时变量(见代码中)
class Program { static void Main(string[] args) { int a = 100, b = 200; Swap1(ref a, ref b); Console.Write("a={0},b={1}", a, b); Console.Read(); Swap2(ref a, ref b); Console.Write("a={0},b={1}", a, b); Console.Read(); } static void Swap1(ref int a, ref int b) { a = b ^ a; b = b ^ a; a = b ^ a; } static void Swap2(ref int a,ref int b) { int tmp; tmp = b; b= a; a = tmp; } }
posted on
浙公网安备 33010602011771号