Take the 2-minute tour ×

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


Most common C# bitwise operations.

share|improve this question
See also: stackoverflow.com/questions/93744/… –  user195488 Dec 18 '09 at 16:42
add comment

7 Answers

up vote 11 down vote accepted

With the & operator

share|improve this answer
add comment

Use the & operator.

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

From MSDN.

share|improve this answer
add comment
var x = 1 & 5;
//x will = 1
share|improve this answer
Since when is var a C# keyword? –  Seva Alekseyev Dec 18 '09 at 16:44
Since C# 3.0 -> msdn.microsoft.com/en-us/library/bb383973.aspx –  Jan Dec 18 '09 at 16:47
In other words, since 2006. –  Joel Mueller Dec 18 '09 at 16:55
@Joel - C#3.0 was released in November 2007 alongside the 3.5 framework –  Lee Dec 18 '09 at 17:08
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? en.wikipedia.org/wiki/.NET_Framework –  Joel Mueller Dec 19 '09 at 8:47
show 1 more comment

use & operator (not &&)

share|improve this answer
add comment
int a = 42;
int b = 21;
int result = a & b;

For a bit more info here's the first Google result:

share|improve this answer
add comment

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;

share|improve this answer
add comment

The & operator

share|improve this answer
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. –  biegleux Aug 26 '12 at 13:12
add comment

Your Answer


