C# 按位和移位运算符

来源:这里教程网 时间:2026-02-21 16:21:15 作者:

c# 按位和移位运算符

按位运算符作用于位,逐位进行运算。

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

运算符 说明 示例
& 按位 AND 运算符将一个位复制到结果(如果两个操作数中都存在)。 (A & B) = 12,即 0000 1100
| 按位或运算符复制一个位(如果任一操作数中存在该位)。 (A | B) = 61,即 0011 1101
^ 按位异或运算符复制该位(如果它在一个操作数中设置,但不是在两个操作数中设置)。 (A ^ B) = 49,即 0011 0001
~ 按位补码运算符是一元的,具有“翻转”位的效果。 (~A ) = 61,由于有符号二进制数,因此为 2 的补码 1100 0011。
按位左移运算符

 左侧操作数的值向左移动右侧操作数指定的位数。

A
>> 按位右移运算符

左操作数的值向右移动右操作数指定的位数。

A >> 2 = 15,即 0000 1111

示例 h2>

以下示例展示了如何在 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

相关推荐