ProgrammingHard
To multiply x by 2^k where x is an unsigned 32-bit value, which code is correct?
- A. x << k, which wraps modulo 2^32 without undefined behaviour
- B. x * (1 << k) with int, which overflows and is undefined
- C. x << 32 when k is 32, which is well defined
- 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
- A program uses a modulus of 10^9 + 7 and computes (a - b + MOD) % MOD for a and b in [0, MOD). Why add MOD before the %?
- What is the value of 5 & 6 | 3 in C?
- What is the value of 0x80 | 0x01 | 0x10 in decimal?
- What is printed? c #include <stdint.h> #include <stdio.h> int main(void) { uint8t a = 0xB6; uint8t b = (uint8t)(a << 3); uint8t c = a >>…
- Assume uint16t is 16 bits, unsigned int is 32 bits and int is 32 bits. What is printed? c #include <stdint.h> #include <stdio.h> int…
- What is printed? c #include <stdio.h> int calls = 0; int f(int n) { calls++; if (n < 2) return n; return f(n - 1) + f(n - 2); } int…