ASCII and bitwise OR on character codes: what five characters are printed? #include<stdio.h> int main() { char c = 48; // ASCII '0' int i, mask = 01; // octal 1 for (i = 1; i <= 5; i++) { printf("%c", c | mask); mask = mask << 1; } return 0; }

Difficulty: Medium

Correct Answer: 12480

Explanation:


Introduction / Context:
This problem blends ASCII knowledge with bitwise operations. The code ORs the code for '0' (48, hex 0x30) with a mask that shifts left each iteration, then prints the resulting character. Recognizing which bit patterns map to digit characters helps.



Given Data / Assumptions:

  • ASCII '0' is 48 → binary 0x30 → 0011 0000.
  • The mask starts at 1 (0000 0001) and shifts left by 1 each loop.
  • Five iterations produce five characters.


Concept / Approach:
ORing sets bits present in either operand. Since 0x30 already has bits 4 and 5 set, ORing with 1, 2, 4, 8, and 16 selectively toggles the low nibble while sometimes leaving the value unchanged if that bit is already 1.



Step-by-Step Solution:
Iter 1: mask=1 → 0x30 | 0x01 = 0x31 → '1'.Iter 2: mask=2 → 0x30 | 0x02 = 0x32 → '2'.Iter 3: mask=4 → 0x30 | 0x04 = 0x34 → '4'.Iter 4: mask=8 → 0x30 | 0x08 = 0x38 → '8'.Iter 5: mask=16 → 0x30 | 0x10 = 0x30 (bit already set) → '0'.



Verification / Alternative check:
Print numeric values instead of %c to verify hex codes: 49, 50, 52, 56, 48 correspond to '1', '2', '4', '8', '0'.



Why Other Options Are Wrong:
'12400', '12500', and '12556' assume different OR results; only the 4th and 5th steps can yield '8' and '0' respectively given the initial 0x30. '13480' incorrectly predicts the third character.



Common Pitfalls:
Assuming left shifts always increase the printed digit; forgetting that OR with an already-set bit leaves the value unchanged (hence the final '0').



Final Answer:
12480

More Questions from Bitwise Operators

Discussion & Comments

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