按位运算符作用于位并执行逐位操作。
以下是按位运算符。
运算符 | 描述 | 例子 |
---|---|---|
& | 如果两个操作数中都存在二进制 AND 运算符,则将其复制到结果中。 | (A & B) = 12, which is 0000 1100 |
| | 如果任一操作数中存在二进制 OR 运算符,则复制一点。 | (A | B) = 61, which is 0011 1101 |
^ | 二进制 XOR 运算符复制该位,如果它在一个操作数中设置,但不能同时在两个操作数中设置。 | (A ^ B) = 49, which is 0011 0001 |
~ | Binary Ones Complement Operator 是一元的,具有“翻转”位的效果。 | (~A ) = 61, which is 1100 0011 in 2's complement due to a signed binary number. |
<< | 二元左移运算符。左操作数值向左移动右操作数指定的位数。 | A << 2 = 240, which is 1111 0000 |
>> | 二元右移运算符。左操作数的值向右移动右操作数指定的位数 | A >> 2 = 15,即 0000 1111 |
下面的示例展示了如何在 C# 中使用按位运算符。
using System; namespace Demo { 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("Value of c is {0}", c ); c = a | b; /* 61 = 0011 1101 */ Console.WriteLine("Value of c is {0}", c); c = a ^ b; /* 49 = 0011 0001 */ Console.WriteLine("Value of c is {0}", c); c = ~a; /*-61 = 1100 0011 */ Console.WriteLine("Value of c is {0}", c); c = a << 2; /* 240 = 1111 0000 */ Console.WriteLine("Value of c is {0}", c); c = a >> 2; /* 15 = 0000 1111 */ Console.WriteLine("Value of c is {0}", c); Console.ReadLine(); } } }输出结果
Value of c is 12 Value of c is 61 Value of c is 49 Value of c is -61 Value of c is 240 Value of c is 15