ProgrammingVery hardProduct company OA

What is printed?

What is printed?
/* 32-bit unsigned int */
unsigned np2(unsigned v) {
    v--;
    v |= v >> 1;  v |= v >> 2;  v |= v >> 4;
    v |= v >> 8;  v |= v >> 16;
    return v + 1;
}
int main(void) {
    printf("%u %u %u %u", np2(37), np2(64), np2(1), np2(0));
}
  1. A. 64 64 1 0
  2. B. 64 128 1 1
  3. C. 32 64 1 0
  4. D. 64 64 2 1

Correct answer: A. 64 64 1 0

After v−−, the OR-shifts copy the highest set bit into every lower position, giving 2^k − 1; adding 1 yields the smallest power of two ≥ the input. 37 → 36 → 63 → 64. 64 → 63 → 63 → 64 (the decrement is what keeps exact powers unchanged). 1 → 0 → 0 → 1. 0 → 0xFFFFFFFF (unsigned wrap) → stays all ones → +1 wraps to 0, so the function's edge case is np2(0) = 0.

More C Programming questions

Exams that ask this topic