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));
}- A. 64 64 1 0
- B. 64 128 1 1
- C. 32 64 1 0
- 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
- What is printed? c / 8-bit unsigned char, 32-bit int / unsigned char c = 0x80; printf("%d %d %d %d", c << 1, (unsigned char)(c << 1), ~c…
- What is printed? c char s[] = "a,b,,c"; int n = 0; for (char t = strtok(s, ","); t; t = strtok(NULL, ",")) n++; printf("%d %zu %c", n…
- What is printed? c char s[] = "Hello"; s[0] = 'J'; s[4] = '0'; printf("%s %zu", s, sizeof(s));
- What is printed? c int i = 5; printf("%d ", i++); printf("%d", ++i);
- What is printed? c printf("%.2f %d %d", 7 / 2.0, 7 / 2, 7 % 2);
- What is printed? c int x = 5; void f(void) { int x = 1; x++; } void g(void) { x++; } int main(void) { f(); g(); g(); printf("%d", x); }