ProgrammingHardTCS NQT · Accenture pattern

What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, ^ is bitwise XOR, << and >> are left and right shifts.) ~ is bitwise NOT in two's complement.

What will be the output of the following pseudocode? (& is bitwise AND, | is bitwise OR, ^ is bitwise XOR, << and >> are left and right shifts.) ~ is bitwise NOT in two's complement.
Integer a = 40
Integer b = a & (~a + 1)
Integer c = a ^ (a - 1)
Print b, c
  1. A. 40 7
  2. B. 32 15
  3. C. 8 15
  4. D. 8 1

Correct answer: C. 8 15

In two's complement, ~a + 1 = -a, and a & -a keeps only the lowest set bit: 40 = 101000, so b = 8. a ^ (a - 1) = 101000 ^ 100111 = 001111 = 15, which is that bit and all the bits below it.

More Pseudocode and Code Tracing questions

Exams that ask this topic