C# 位運算子和位移運算子
位運算子作用於位,並執行逐位操作。
C# 支援的位運算子列在下表中。假設變數 A 為 60,變數 B 為 13:
運算子 | 描述 | 示例 |
---|---|---|
& | 按位與運算子:如果位在兩個運算元中都存在,則將其複製到結果中。 | (A & B) = 12,即 0000 1100 |
| | 按位或運算子:如果位在任一運算元中存在,則將其複製。 | (A | B) = 61,即 0011 1101 |
^ | 按位異或運算子:如果位在一個運算元中設定,但在另一個運算元中未設定,則複製該位。 | (A ^ B) = 49,即 0011 0001 |
~ | 按位取反運算子:是一元運算子,其作用是“翻轉”位。 | (~A) = -61,在二進位制補碼中為 1100 0011,因為這是一個帶符號的二進位制數。 |
<< | 按位左移運算子 左運算元的值向左移動由右運算元指定的位數。 | A << 2 = 240,即 1111 0000 |
>> | 按位右移運算子 左運算元的值向右移動由右運算元指定的位數。 | A >> 2 = 15,即 0000 1111 |
示例
以下示例演示如何在 C# 中實現位運算子。
using System; namespace MyApplication { class Program { static void Main(string[] args) { int a = 60; /* 60 = 0011 1100 */ int b = 13; /* 13 = 0000 1101 */ int c = 0; // Bitwise AND Operator c = a & b; /* 12 = 0000 1100 */ Console.WriteLine("Line 1 - Value of c is {0}", c ); // Bitwise OR Operator c = a | b; /* 61 = 0011 1101 */ Console.WriteLine("Line 2 - Value of c is {0}", c); // Bitwise XOR Operator c = a ^ b; /* 49 = 0011 0001 */ Console.WriteLine("Line 3 - Value of c is {0}", c); // Bitwise Complement Operator c = ~a; /*-61 = 1100 0011 */ Console.WriteLine("Line 4 - Value of c is {0}", c); // Bitwise Left Shift Operator c = a << 2; /* 240 = 1111 0000 */ Console.WriteLine("Line 5 - Value of c is {0}", c); // Bitwise Right Shift Operator 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
廣告