Tony The Lion
Tony The Lion

Reputation: 63310

Bitwise AND on 32-bit Integer

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

Related:

Most common C# bitwise operations.

Upvotes: 17

Views: 45510

Answers (8)

George Polevoy
George Polevoy

Reputation: 7681

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;

Upvotes: 0

bitlather
bitlather

Reputation: 640

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

Upvotes: 2

mcintyre321
mcintyre321

Reputation: 13316

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

Upvotes: 3

Jim C
Jim C

Reputation: 4981

The & operator

Upvotes: 0

rui
rui

Reputation: 11284

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

Upvotes: 0

jason
jason

Reputation: 241779

Use the & operator.

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

From MSDN.

Upvotes: 6

Jim L
Jim L

Reputation: 2327

use & operator (not &&)

Upvotes: 0

David M
David M

Reputation: 72930

With the & operator

Upvotes: 23

Related Questions