[Solved] what does this expression mean “val&=val-1” [duplicate]


val is initialized to

val = x ^ y;

i.e. val is the bit-wise XOR of x and y, which means it contains 1 in all the bits where x and y differ and 0 in all the bits where x and y are the same.

Now, each iteration of the loop performs

val &= val - 1;

which is equivalent to

val = val & (val - 1);

Each such bit-wise AND operation turns a single 1 bit of val to 0.

For example, suppose the binary representation of val is:

1010

The binary representation of val - 1 is:

1001

and after performing bit-wise AND, we get:

1000

Therefore, by the end of the loop, dist contains the number of 1 bits in the original value of val, which is the number of bits by which x and y differ.

solved what does this expression mean “val&=val-1” [duplicate]