ProgrammingHard

To multiply x by 2^k where x is an unsigned 32-bit value, which code is correct?

  1. A. x << k, which wraps modulo 2^32 without undefined behaviour
  2. B. x * (1 << k) with int, which overflows and is undefined
  3. C. x << 32 when k is 32, which is well defined
  4. D. x >> -k, which is equivalent

Correct answer: A. x << k, which wraps modulo 2^32 without undefined behaviour

Unsigned left shifts wrap defined modulo the width as long as k is below 32. Shifting an int into its sign bit or by a width of 32 is undefined.

More C Programming questions

Exams that ask this topic