Bitwise AND of two Chars prints wrong result

132 Views Asked by At

When I run this code -

string binNumber="11111000001";
for(int ind=0; ind<binNumber.Length; ind++){
   Console.WriteLine(binNumber[ind]&'1');
}

it prints sequence of 49 and 48 instead of 1 and 0.

I could not understand why is it happening? If I use the XOR operator it prints 1s & 0s. I have seen this behavior for & and | operator. The code can be accessed in the IdeOne here - https://ideone.com/fqZFUY.

2

There are 2 best solutions below

4
On BEST ANSWER

'0' has a code of 48 in decimal, or 110000 in binary.

'1' has a code of 49 in decimal, or 110001 in binary.

110000 & 110001 == 110000 == 48 decimal

110001 & 110001 == 110001 == 49 decimal

So when you do Console.WriteLine(binNumber[ind]&'1'); you get 48 or 49 depending on whether binNumber[ind] is '0' or '1'.

Remember that if you do someChar & someOtherChar the compiler does a bitwise AND of the numeric values of those chars.

0
On

The type of an & operation between two char is int. You can see it if you try:

var res = '0' & '0';

and you look at the type of res. (technically this is called "binary numeric promotion", and what happens in this case is that both char are converted to int, then the & is done between two int, and clearly the result is an int. If you are interested it is explained here)

So being the result an int, Console.WriteLine formats it as an int.

Try

Console.WriteLine((char)(binNumber[ind]&'1'));