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
Bitwise AND on 32-bit Integer
提问by Tony The Lion
How do you perform a bitwise AND operation on two 32-bit integers in C#?
如何在 C# 中对两个 32 位整数执行按位与运算?
Related:
有关的:
采纳答案by David M
With the & operator
使用 & 运算符
回答by Jim L
use & operator (not &&)
使用 & 运算符(不是 &&)
回答by jason
回答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
The & operator
在与运营商
回答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 */ }