目录

Show 例子

C#支持的Bitwise运算符如下表所示。 假设变量A保持60,变量B保持13,则 -

操作者 描述
& 如果二进制AND运算符存在于两个操作数中,则它会将结果复制到结果中。 (A&B)= 12,即0000 1100
| 二进制OR运算符如果存在于任一操作数中,则复制一位。 (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

例子 (Example)

以下示例演示了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
↑回到顶部↑
WIKI教程 @2018