C# 中的位运算符是什么?

csharpprogrammingserver side programming更新于 2025/9/20 11:37:17

位运算符作用于位,并执行逐位运算。

以下是位运算符。

运算符描述示例
&如果二进制"与"运算符在两个操作数中都存在,则将一位复制到结果中。(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 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

相关文章