【问题标题】:In c# what does the ^ character do? [duplicate]在 C# 中,^ 字符有什么作用? [复制]
【发布时间】:2011-07-08 17:40:46
【问题描述】:

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

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

【问题讨论】:

  • “^”在 C# 中的另一个用法,或者至少出现在整个 .NET 文档中而没有任何解释的用法是“对象运算符的句柄”。这是一个 C++ 的东西,它标记了一个垃圾收集的对象,所以你不必自己担心内存管理。它遍布 MSDN .NET 文档,例如SomeMethod(String^, IDictionary<String^, Object^>^),但实际上并没有在任何地方解释。在 Google 或 SE 中出现的关于 C# 中“^”的唯一内容是“XOR”的答案,这是完全不同的。 msdn.microsoft.com/en-us/library/yk97tc08.aspx

标签: c#


【解决方案1】:

这是二进制XOR 运算符。

二进制 ^ 运算符是为 整数类型和布尔值。为了 整数类型,^ 按位计算 其操作数的异或。对于布尔 操作数,^ 计算逻辑 其操作数的异或;那是, 结果为真当且仅当 它的一个操作数恰好是真的。

【讨论】:

    【解决方案2】:

    ^ 字符或“插入符号”字符是按位异或运算符。 例如

    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

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        【讨论】:

          猜你喜欢
          • 2010-10-04
          • 2011-05-19
          • 1970-01-01
          • 1970-01-01
          • 2011-05-26
          • 2011-04-18
          • 2016-05-31
          • 2015-10-15
          相关资源
          最近更新 更多