简体   繁体   English

在32位整数上按位与

[英]Bitwise AND on 32-bit Integer

How do you perform a bitwise AND operation on two 32-bit integers in C#? 如何在C#中对两个32位整数执行按位与运算?

Related: 有关:

Most common C# bitwise operations. 最常见的C#按位运算。

与&运算符

Use the & operator. 使用&运算符。

Binary & operators are predefined for the integral types[.] For integral types, & computes the bitwise AND of its operands. 对于整数类型[。]预定义了二进制&运算符。对于整数类型,&计算其操作数的按位与。

From MSDN . 来自MSDN

var x = 1 & 5;
//x will = 1
const uint 
  BIT_ONE = 1,
  BIT_TWO = 2,
  BIT_THREE = 4;

uint bits = BIT_ONE + BIT_TWO;

if((bits & BIT_TWO) == BIT_TWO){ /* do thing */ }

使用&运算符(不是&&)

int a = 42;
int b = 21;
int result = a & b;

For a bit more info here's the first Google result: 有关更多信息,这是Google的第一个结果:
http://weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not.aspx http://weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not.aspx

var result = (UInt32)1 & (UInt32)0x0000000F;

// result == (UInt32)1;
// result.GetType() : System.UInt32

If you try to cast the result to int, you probably get an overflow error starting from 0x80000000, Unchecked allows to avoid overflow errors that not so uncommon when working with the bit masks. 如果尝试将结果强制转换为int,则可能会收到从0x80000000开始的溢出错误,而Unchecked可以避免使用位掩码时不太常见的溢出错误。

result = 0xFFFFFFFF;
Int32 result2;
unchecked
{
 result2 = (Int32)result;
}

// result2 == -1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM