How do you perform a bitwise AND operation on two 32-bit integers in C#?
Bitwise AND on 32-bit Integer
Asked Answered
Use the &
operator.
Binary & operators are predefined for the integral types[.] For integral types, & computes the bitwise AND of its operands.
From MSDN.
var x = 1 & 5;
//x will = 1
Since when is var a C# keyword? –
Bowstring
@Joel - C#3.0 was released in November 2007 alongside the 3.5 framework –
Biernat
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 –
Hamstring
@SevaAlekseyev to be more exact, it's a contextual keyword; whether it's a keyword depends on where it's used. For example,
class var { }
is perfectly fine. –
Hutchens 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 */ }
Hiya, this may well solve the problem... but it'd be good if you could provide a little explanation about how and why it works :) Don't forget - there are heaps of newbies on Stack overflow, and they could learn a thing or two from your expertise - what's obvious to you might not be so to them. –
Quiescent
It'd also be worth indicating which part of this answer addresses the question "How do you perform a bitwise AND operation on two 32-bit integers in C#?". Your answer appears to assume that the asker is using flags, but there's no reason why that would be the case. You should also think about whether your answer adds anything that hasn't already been addressed by the other answers. In my opinion, it doesn't. –
Vmail
I learned development by analyzing code samples. I think this gives more information than the top rated answer, "Use the & operator." It presents a template for how to compare multiple bits. It also uses constants instead of literals. I posted this mostly because I haven't touched C# in a while and needed it for a project of my own. Instead of asking & answering my own question, I placed it here. Seriously, "use & operator (not &&)" is now higher rated than my response? –
Waitress
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
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;
© 2022 - 2024 — McMap. All rights reserved.