Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange results when & is used in conjunction of two integers C# [duplicate]

Tags:

c#

.net

I am not able to understand whats happening and how this result from the following lines:

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

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

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

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

I don't know the significance of & and the significance of & in this context. How the results above are manipulated? Whats the logic?

like image 564
Jasmine Avatar asked Dec 12 '22 15:12

Jasmine


1 Answers

Bitwise arithmetic:

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

where & follows the truth-table (per-bit):

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

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

like image 168
Marc Gravell Avatar answered Mar 09 '23 01:03

Marc Gravell