位操作符是对数据按二进制位进行运算的操作符。c#位操作符包括:
- 按位与 &
- 按位或 |
- 按位取反 ~
- 左移 <<
- 右移 >>
举例说明
using System;
class MikeCat
{
public static void Main()
{
int a=6&3;
Console.WriteLine("a={0}",a);
//6的二进制是00000110,3的二进制是00000011,按位与后等于00000010, 即2。
int b=6|3;
Console.WriteLine("b={0}",b);
//6的二进制是00000110,3的二进制是00000011,按位或后等于00000111,即7
int c=~6;
Console.WriteLine("c={0}",c);
//6的二进制是00000110,按位取反后是11111001即-7
int d=6^3;
Console.WriteLine("d={0}",d);
//6的二进制是00000110,3的二进制是00000011,按位异或后等于00000101,即5
int e=6<<3;
Console.WriteLine("e={0}",e);
//6的二进制是00000110,左移三位后等于00101000,即48
int f=6>>2;
Console.WriteLine("f={0}",f);
//6的二进制是00000110,右移二位等于00000001,即1
}
}
using System;
class MikeCat
{
public static void Main()
{
int a=6&3;
Console.WriteLine("a={0}",a);
//6的二进制是00000110,3的二进制是00000011,按位与后等于00000010, 即2。
int b=6|3;
Console.WriteLine("b={0}",b);
//6的二进制是00000110,3的二进制是00000011,按位或后等于00000111,即7
int c=~6;
Console.WriteLine("c={0}",c);
//6的二进制是00000110,按位取反后是11111001即-7
int d=6^3;
Console.WriteLine("d={0}",d);
//6的二进制是00000110,3的二进制是00000011,按位异或后等于00000101,即5
int e=6<<3;
Console.WriteLine("e={0}",e);
//6的二进制是00000110,左移三位后等于00101000,即48
int f=6>>2;
Console.WriteLine("f={0}",f);
//6的二进制是00000110,右移二位等于00000001,即1
}
}
轉自別處