C# - 位運算子



C# 支援的位運算子列在下面的表格中。假設變數 A 為 60,變數 B 為 13,則 -

運算子 描述 示例
& 按位與運算子如果兩個運算元中都存在一個位,則將其複製到結果中。 (A & B) = 12,即 0000 1100
| 按位或運算子如果任一運算元中存在一個位,則將其複製。 (A | B) = 61,即 0011 1101
^ 按位異或運算子如果一個運算元中設定了一個位,但不是兩個運算元都設定,則複製該位。 (A ^ B) = 49,即 0011 0001
~ 按位取反運算子是一元運算子,其作用是“翻轉”位。 (~A ) = -61,由於帶符號二進位制數,在 2 的補碼中為 1100 0011。
<< 左移位運算子。左運算元的值向左移動由右運算元指定的位數。 A << 2 = 240,即 1111 0000
>> 右移位運算子。左運算元的值向右移動由右運算元指定的位數。 A >> 2 = 15,即 0000 1111

示例

以下示例演示了 C# 中可用的所有位運算子 -

using System;

namespace OperatorsAppl {

   class Program {
   
      static void Main(string[] args) {
         int a = 60;            /* 60 = 0011 1100 */ 
         int b = 13;            /* 13 = 0000 1101 */
         int c = 0; 
         
         c = a & b;             /* 12 = 0000 1100 */ 
         Console.WriteLine("Line 1 - Value of c is {0}", c );
         
         c = a | b;             /* 61 = 0011 1101 */
         Console.WriteLine("Line 2 - Value of c is {0}", c);
         
         c = a ^ b;             /* 49 = 0011 0001 */
         Console.WriteLine("Line 3 - Value of c is {0}", c);
         
         c = ~a;                /*-61 = 1100 0011 */
         Console.WriteLine("Line 4 - Value of c is {0}", c);
         
         c = a << 2;      /* 240 = 1111 0000 */
         Console.WriteLine("Line 5 - Value of c is {0}", c);
         
         c = a >> 2;      /* 15 = 0000 1111 */
         Console.WriteLine("Line 6 - Value of c is {0}", c);
         Console.ReadLine();
      }
   }
}

編譯並執行上述程式碼後,將產生以下結果 -

Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
csharp_operators.htm
廣告
© . All rights reserved.