C# 32 位整数上的按位与

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1929343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:56:50  来源:igfitidea点击:

Bitwise AND on 32-bit Integer

c#bitwise-and

提问by Tony The Lion

How do you perform a bitwise AND operation on two 32-bit integers in C#?

如何在 C# 中对两个 32 位整数执行按位与运算?

Related:

有关的:

Most common C# bitwise operations.

最常见的 C# 按位运算。

采纳答案by David M

With the & operator

使用 & 运算符

回答by Jim L

use & operator (not &&)

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

回答by jason

Use the &operator.

使用&运算符。

Binary & operators are predefined for the integral types[.] For integral types, & computes the bitwise AND of its operands.

二进制 & 运算符是为整数类型预定义的 [.] 对于整数类型, & 计算其操作数的按位与。

From MSDN.

来自MSDN

回答by mcintyre321

var x = 1 & 5;
//x will = 1

回答by rui

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

For a bit more info here's the first Google result:
http://weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not.aspx

有关更多信息,请参阅第一个 Google 结果:http:
//weblogs.asp.net/alessandro/archive/2007/10/02/bitwise-operators-in-c-or-xor-and-amp-amp-not .aspx

回答by Jim C

回答by George Polevoy

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;

回答by bitlather

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 */ }