C# Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - General Questions (Q.No. 14)
14.
What will be the output of the C#.NET code snippet given below?
int i = 2, j = i;
if (Convert.ToBoolean((i | j & 5) & (j - 25 * 1)))
    Console.WriteLine(1); 
else
    Console.WriteLine(0);
0
1
Compile Error
Run time Error
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
9 comments Page 1 of 1.

Joao Lourenco said:   1 decade ago
(i | j & 5) & (j - 25 * 1)
(2 | 2 & 5) & (2 - 25 * 1)
(2 | 2 & 5) & (-23)

Convert to binary:
(10 | 10 & 101) & 111111111111111111111111101001
(10 | 0) & 111111111111111111111111101001
10 & 111111111111111111111111101001
0

Note: to convert a negative to binary, convert it to a positive value's binary representation and make sure that if you add this value to your negative representation, it causes a rollover e.g.
1: 1
-1 : 11111111111111111111111111111111

2: 10
-2 : 11111111111111111111111111111110

Jay said:   7 years ago
The question is about operator precedence and bitwise logic including how negative numbers are represented.
= (i | j & 5) & (j - 25 * 1)

Left side parenthesis
= 2 | 2 & 5
= 00000010 | 00000010 & 00000101 (AND 1st),
= 00000010 | 00000000 (OR 2nd),
= 00000010.

Rightside parenthesis;
= 2 - 25 * 1 (Multiply 1st),
= 2 - 25 (Subtract 2nd).
= -23.
= 11101001 (Two's complement, the rule is take the positive value, subtract 1 and flip the bits).

Together;
= 00000010 & 11101001,
= 00000000.
= 0 (decimal).

Stephanie H said:   8 years ago
I believe You're only supposed to understand how negative binary numbers work.
as in, negative binary always equals 0.

The following code is evidence of that, " Console.WriteLine(1); else Console.WriteLine(0);"

The WriteLine only wants us to know if the number is 1 (positive) or 0 (negative).

This Formula is filled with negative values ( (j - 25 * 1) so just looking at it and understand how negative numbers work we are able to figure out the solution in no time.

VKG said:   9 years ago
Let me know about the precedence first it will take braces and then according to your solution it's taking the right to left so as per your answer first it is evaluating & and then |.
Can you explain these things in better way?

Anubhav said:   10 years ago
Just find the Two's complement of the negative number i.e., 23 (which is finding the binary of 23, complement it, and then add 1 to it).

Perform AND it with the expression on the Left Hand Side gives the output as 0.

Anshul jain said:   10 years ago
Explain in detail? I am not understand.

Janki said:   1 decade ago
Please explain how the answer came.

Chetan said:   5 years ago
Nicely explained, thanks @Jay.
(1)

Yogesh Burte said:   10 years ago
I am also not understand.

Post your comments here:

Your comments will be displayed after verification.