2011-03-04 85 views
11

可能重複:
What are the | and^operators used for?在c#中^字符做了什麼?

在C#是什麼^字符呢?

+0

http://stackoverflow.com/q/3735623 – Alex 2011-03-04 10:42:46

+5

的 「^」 在C#,或其中至少整個.NET文檔顯示沒有任何解釋,是「處理的附加使用以反對運營商。「這是一個標記垃圾收集對象的C++事物,因此您不必擔心自己的內存管理問題。它遍佈MSDN .NET文檔,例如'SomeMethod(String ^,IDictionary ^)',但實際上並沒有在任何地方解釋。在Google或SE中出現的關於C#中「^」的唯一情況就是「XOR」的答案,這是完全不同的。 https://msdn.microsoft.com/en-us/library/yk97tc08.aspx – mc01 2017-05-09 20:21:10

+0

這是我正在尋找的答案。 – 2017-05-31 21:13:10

回答

14

這是二進制XOR運算符。

二進制^運算符是爲 預定義的整型和布爾值。對於 整型,^計算其操作數的異或運算。對於bool 操作數,^計算邏輯 排斥或其操作數;即 只有當其中一個操作數爲真時 結果爲真。

4

^字符或'caret'字符是一個按位XOR操作符。 例如

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