C#.NET — Determine the printed output by evaluating bitwise precedence and Convert.ToBoolean. int i = 2, j = i; if (Convert.ToBoolean((i | (j & 5)) & (j - 25 * 1))) Console.WriteLine(1); else Console.WriteLine(0);
-
A0
-
B1
-
CCompile Error
-
DRun time Error
Answer
Correct Answer: 0
Explanation
Introduction / Context:This question checks precedence of bitwise operators, arithmetic evaluation, and the effect of Convert.ToBoolean on integer values in C#.
Given Data / Assumptions:
- i = 2, j = 2
- Expression: Convert.ToBoolean((i | j & 5) & (j - 25 * 1))
- Console prints 1 if the boolean is true, otherwise 0.
Concept / Approach:Operator precedence: & (bitwise AND) binds tighter than | (bitwise OR). Arithmetic executes before bitwise. Convert.ToBoolean(x) is true for any nonzero integer and false for zero.
Step-by-Step Solution:
Compute j & 5 first: 2 & 5 = 0. Compute i | (that): 2 | 0 = 2. Compute (j - 25 * 1): 2 - 25 = -23. Now evaluate 2 & (-23). In two's complement, -23 has a 0 bit in the 2's place, so 2 & (-23) = 0. Convert.ToBoolean(0) == false; therefore, the else branch runs and prints 0.Verification / Alternative check:You can reason by bit positions: value 2 has only the 2's bit set; -23 ends with ...1001 (for -23 it is 1111...1110 1001), making the 2's bit 0; their AND is 0.
Why Other Options Are Wrong:
- 1: would require a nonzero result after the final &.
- Compile Error / Run time Error: the code is valid and runs without exceptions.
Common Pitfalls:Mixing up logical && with bitwise &, and assuming negative & positive is always nonzero. It depends on overlapping set bits.
Final Answer:0