在c#中^字符有什么作用?

时间:2011-03-04 10:39:27

标签: c#

  

可能重复:
  What are the | and ^ operators used for?

在c#中^字符有什么作用?

4 个答案:

答案 0 :(得分:16)

这是二元XOR运算符。

  

二进制^运算符是预定义的   积分类型和布尔。对于   积分类型,^按位计算   其操作数的异或。对于布尔   操作数,^计算逻辑   独家或其操作数;那是,   结果是真的,当且仅当   其中一个操作数是真的。

答案 1 :(得分:5)

^字符或'caret'字符是按位XOR运算符。 e.g。

using System;

class Program
{
    static void Main()
    {
        // Demonstrate XOR for two integers.
        int a = 5550 ^ 800;
        Console.WriteLine(GetIntBinaryString(5550));
        Console.WriteLine(GetIntBinaryString(800));
        Console.WriteLine(GetIntBinaryString(a));
        Console.WriteLine();

        // Repeat.
        int b = 100 ^ 33;
        Console.WriteLine(GetIntBinaryString(100));
        Console.WriteLine(GetIntBinaryString(33));
        Console.WriteLine(GetIntBinaryString(b));
    }

    /// <summary>
    /// Returns binary representation string.
    /// </summary>
    static string GetIntBinaryString(int n)
    {
        char[] b = new char[32];
        int pos = 31;
        int i = 0;

        while (i < 32)
        {
            if ((n & (1 << i)) != 0)
            {
                b[pos] = '1';
            }
            else
            {
                b[pos] = '0';
            }
            pos--;
            i++;
        }
        return new string(b);
    }
}

^^^ Output of the program ^^^

00000000000000000001010110101110
00000000000000000000001100100000
00000000000000000001011010001110

00000000000000000000000001100100
00000000000000000000000000100001
00000000000000000000000001000101

http://www.dotnetperls.com/xor

答案 2 :(得分:1)

答案 3 :(得分:0)