-1

I don't understand why below doesn't work.

I've tried everything I can do - but no progress.

int b = 0;
int x = (1<<1)|(1<<2)|(1<<3)
do {
    // process subset
} while((b=(b-x)&x));

What I wonder is that expression b=(b-x)&x iterate all subsets.

I searched google like 'bit manipulation' or 'bit subset iterate' but there's no answer or hints.

Please help me.

Even Stackoverflow don't have this question. at all..

Rot-man
  • 18,045
  • 12
  • 118
  • 124
fian Elf
  • 13
  • 4

1 Answers1

0

this question is horribly asked, I would recommend you to rewrite and clarify what exactly are you asking

meanwhile when doing bit-wise operations you must be familiar with binary representation and specifically to this case two's-compliment representation of negative numbers

x is initialized as b'1110 and in decimal representation 14 so let's examine the first iteration b = (b - x) & x

first, since b=0 and x=14 then (b-x) = -14 or in two's compliment ...111110010

second, with the x masking the result will be (consider just the 4 LSBs) 0010 & 1110 so the result after the first iteration: b=b'0010=d'2

you can try and run this code with prints to understand the iteration process - it usually makes things more understandable:

int counter = 0;
int b = 0;
int x = (1<<1)|(1<<2)|(1<<3);
printf("init x: %x\n", x);
do {
    printf("iteration:%d subset:%x\n",counter++, b);
    printf(" intermediate(b-x): %x\n", (b-x));
} while((b=(b-x)&x));

With all that said... WHAT IS THE QUESTION?

Omer Dagan
  • 662
  • 5
  • 14