ProgrammingHardGATE CS

What is the value printed? Assume unsigned int is 32 bits.

What is the value printed? Assume unsigned int is 32 bits.
#include <stdio.h>
int main(void) {
    unsigned x = 0xB6D9 ^ 0x00FF;
    int n = 0;
    while (x) {
        x &= x - 1;
        n++;
    }
    printf("%d", n);
    return 0;
}
  1. A. 8
  2. B. 6
  3. C. 9
  4. D. 10

Correct answer: A. 8

x &= x - 1 clears the lowest set bit, so the loop counts the set bits of x. 0xB6D9 ^ 0x00FF = 0xB626 = 1011 0110 0010 0110 in binary, which has 3 + 2 + 1 + 2 = 8 ones (the original 0xB6D9 has 10).

More C Programming questions

Exams that ask this topic