tags:

views:

172

answers:

7

How do you perform a BitWise AND on 2 32 bit integers in C#?

Related:

Most common C# bitwise operations

+7  A: 

With the & operator

David M
A: 

use & operator (not &&)

Jim Leonardo
+2  A: 

Use the & operator.

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

From MSDN.

Jason
+1  A: 

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

mcintyre321
Since when is var a C# keyword?
Seva Alekseyev
Since C# 3.0 -> http://msdn.microsoft.com/en-us/library/bb383973.aspx
Jan
In other words, since 2006.
Joel Mueller
@Joel - C#3.0 was released in November 2007 alongside the 3.5 framework
Lee
My mistake, I presumed that C# 3.0 was released at the same time as .NET 3.0, in November 2006. Why would they ship C# 3.0 with .NET 3.5 but not .NET 3.0? http://en.wikipedia.org/wiki/.NET_Framework
Joel Mueller
A: 
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

ruibm
A: 

The & operator

Jim C
A: 

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.

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

// result2 == -1;

George Polevoy