ProgrammingHardGATE CS · TCS NQT
How many values x in 0..255 satisfy (x & (uint8t)-x) == x? Assume uint8t is 8 bits.
How many values x in 0..255 satisfy (x & (uint8_t)-x) == x? Assume uint8_t is 8 bits.
#include <stdint.h>
#include <stdio.h>
int main(void) {
int c = 0;
for (unsigned x = 0; x < 256; x++) {
uint8_t ux = (uint8_t)x;
uint8_t neg = (uint8_t)-ux;
if ((uint8_t)(ux & neg) == ux) c++;
}
printf("%d", c);
}- A. 9
- B. 8
- C. 1
- D. 255
Correct answer: A. 9
x & -x isolates the lowest set bit, so it equals x only when x has at most one set bit: 0 and the eight powers of two, 9 values. 8 forgets x = 0, 1 treats -x as ~x (x & ~x is always 0), and 255 assumes every nonzero x passes.
More C Programming questions
- What is printed? c #include <stdio.h> int f(int n) { static int calls = 0; calls++; if (n <= 0) return calls; int r = f(n - 2); return r…
- What is printed? c #include <stdio.h> struct P { int v; }; int main(void) { struct P arr[3] = {{1}, {2}, {3}}; int sum = 0; for (struct P…
- What is printed? c #include <stdio.h> int main(void) { char c = 'a'; printf("%d %d", c + 1 == 'b', '9' - '0'); }
- What is printed? c #include <stdio.h> unsigned fibcalls = 0; int fib(int n) { fibcalls++; if (n < 2) return n; return fib(n - 1) + fib(n…
- What is printed for the sorted array below? c #include <stdio.h> int main(void) { int a[] = {1, 3, 3, 3, 5, 8}; int n = 6, lo = 0, hi = n…
- What is printed? c #include <stdio.h> int find(const char hay, const char nd) { for (const char p = hay; p; p++) { const char a = p, b =…