Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise Or: C# versus C++

). Assume you have two integers, a = 8, b = 2. In C++ a | b is true. I used that behavior to work with collections of flags. For example the flags would be 1, 2, 4, 8 and so on, and any collection of them would be unique. I can't find how to do that in C#, as the | and & operators don't behave like they would in C++. I read documentation about operators in C# but I still don't get it.

EDIT:

Unfortunately, I seem to mess things up somewhere. Take this code for example:

byte flagCollection = 8;
byte flag = 3;

if ((flag | flagCollection) != 0) MessageBox.Show("y"); else MessageBox.Show("n");

This returns "y" for whatever value I put in flag. Which is obvious, because 3 | 8 would be 11. Hmmmm... what I want to do is have a flag collection: 1, 2, 4, 8, 16 and when I give a number, to be able to determine what flags is it.

like image 942
Axonn Avatar asked Dec 12 '09 20:12

Axonn


2 Answers

The & and | operators in C# are the same as in C/C++. For instance, 2 | 8 is 10 and 2 & 8 is 0.

The difference is that an int is not automatically treated like a boolean value. int and bool are distinct types in C#. You need to compare an int to another int to get a bool.

if (2 & 8) ...         //  doesn't work

if ((2 & 8) != 0) ...  //  works
like image 152
dtb Avatar answered Sep 20 '22 23:09

dtb


It's not the bitwise and/or operators that are different in C#. They work almost the same as in C++. The difference is that in C# there isn't an implicit conversion from integer to a boolean.

To fix your problem you just need to compare to zero:

if ((a | b) != 0) {
   ...
like image 23
Mark Byers Avatar answered Sep 22 '22 23:09

Mark Byers