Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# & operator clarification

Tags:

c#

.net

logic

I saw a couple of questions here about the diference between && and & operators in C#, but I am still confused how it is used, and what outcome results in different situations. For example I just glimpsed the following code in a project

bMyBoolean = Convert.ToBoolean(nMyInt & 1);
bMyBoolean = Convert.ToBoolean(nMyInt & 2);

When it will result 0 and when >0? What is the logic behind this operator? What are the diferences between the operator '|'?

bMyBoolean = Convert.ToBoolean(nMyInt | 1);
bMyBoolean = Convert.ToBoolean(nMyInt | 2);

Can we use the &&, || operators and get the same results (possibly with different code)?

like image 780
Sunscreen Avatar asked Sep 26 '12 10:09

Sunscreen


3 Answers

The && is a conditional and used in if statements and while

if(x>1 && y<3)

this means that x should be greater than 1 and y less than 3, satisfy both conditions

if(x>1 || y<3)

satisfy one of them

However, & and | are bitwise AND and OR respectively. ex:

 1 | 0  => 1
 1 & 0  => 0
 1 & 1  => 1

if this apply for straight integers, their corresponding binary value will be calculated and applied

2&1
=>   10  // the binary value of 2
     &
     01  // the binary value of 1
     --
     00  // the result is zero
like image 177
Sleiman Jneidi Avatar answered Oct 19 '22 02:10

Sleiman Jneidi


The ampersand does bitwise AND on the integers in their binary representations. The pipe does bitwise OR.

See here what those bitwise operations mean: http://en.wikipedia.org/wiki/Bitwise_operation

like image 40
Tomas Grosup Avatar answered Oct 19 '22 03:10

Tomas Grosup


& and | is bit operations. You must use it on bit masks. && and || is logical operations so you can use it for only bool values.

Example of bit operation:

var a = 1;
var b = 2;
var c = a|b;

in binary format this means a = 00000001, b = 00000010 c = 00000011

So if you use bitmask c it will pass values 1, 2 or 3.

like image 30
Kirill Bestemyanov Avatar answered Oct 19 '22 02:10

Kirill Bestemyanov