Strange results when & is used in combination of two C # integers

I can’t understand what is happening and how it comes from the following lines:

Example 1: I get 1 as the result for below.

int a = 1, b = 9; int r = a & b; Console.WriteLine(r); 

Example 2: I get 8 as the result for below.

 int a = 10, b = 9; int r = a & b; Console.WriteLine(r); 

I do not know the meaning of & and the meaning of & in this context. How are the results processed above? What is the logic?

+4
source share
5 answers

Bitwise Arithmetic:

 9 = 1001 9 = 1001 1 = 0001 10 = 1010 -------- --------- & = 0001 = 1 & = 1000 = 8 

where & follows the truth table (bit):

 & | 0 1 --+---- 0 | 0 0 1 | 0 1 

i.e. "outputs 1 only if both inputs 1"

+10
source

From & Operator (C# Reference)

For integral types, & computes the logical bitwise AND of its operands.

Truth table for &

 & | 0 1 --+---- 0 | 0 0 1 | 0 1 

When you write 1 & 9 , the result will be 1 , because it works like this:

 0001 1001 x--------------- 0001 

When you write 10 & 9 , the result will be 8 because it works like;

 1010 1001 x--------------- 1000 
+2
source

This is the named operator & (AND) .

Bitwise and operator changes bits. It provides important functionality for bitwise logic. When it is applied to two numbers, the result is another number that contains 1, where each of the two numbers also have 1.

Also see: & Operator (link to C #)

For you, the case when int a = 1, b = 9; int r = a and b;

 a: 0001 (binary equvivalent of 1) b: 1001 (binary equvivalent of 9) ---------- r: 0001 (which would be 1) 
+1
source

Here is an example:

  3: 0011 1: 0001 3 & 1: 0001 
0
source

int r = a and b; // a = 1, b = 9

First example:

 a: 0 0 0 1 b: 1 0 0 1 r: 0 0 0 1 // 1 

Second example:

 a: 1 0 1 0 b: 1 0 0 1 r: 1 0 0 0 // 8 

& (AND-operator) means that the result (r) is only 1 when a and b are equal to 1. Otherwise, it is 0.

0
source

All Articles