C# bitwise NOT, shifts, and promotions — predict the output byte b1 = 0xAB; byte b2 = 0x99; byte temp; temp = (byte)~b2; Console.Write(temp + ' '); temp = (byte)(b1 << b2); Console.Write(temp + ' '); temp = (byte)(b2 >> 2); Console.WriteLine(temp);

Difficulty: Medium

Correct Answer: 102 0 38

Explanation:


Introduction / Context:
This snippet combines bitwise NOT (~), left and right shifts, and type promotion rules for byte in C#. Predicting the output requires careful attention to how shift counts work and how casting back to byte truncates.



Given Data / Assumptions:

  • b1 = 0xAB (171), b2 = 0x99 (153).
  • byte is promoted to int for operators; cast back to byte truncates to the low 8 bits.
  • For int shifts, only the low 5 bits of the shift count are used (count mod 32).


Concept / Approach:
Compute each line independently, remembering promotions and shift-count masking.



Step-by-Step Solution:

1) ~b2 → ~0x99 = 0x66 (binary inversion of 10011001 is 01100110) → 102 decimal.2) b1 << b2 → shift count = 153 mod 32 = 25; (int)0xAB << 25 pushes all significant bits out of the low byte → when cast to byte, result is 0.3) b2 >> 2 → 0x99 (153) >> 2 = 0x26 (38) for logical effect after cast to byte (byte promoted to int, right shift on positive int is arithmetic; for 153 it matches logical).


Verification / Alternative check:
Use a small console program to print each intermediate value in hex and decimal; confirm 0x66, 0x00, 0x26.



Why Other Options Are Wrong:
They miscompute the complement, ignore shift-count masking, or mis-handle the cast back to byte.



Common Pitfalls:
Forgetting that shifting by a large number is masked mod 32 for int; expecting left shift to wrap instead of truncating when cast back to byte.



Final Answer:
102 0 38

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion