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);
}
  1. A. 9
  2. B. 8
  3. C. 1
  4. 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

Exams that ask this topic