basically trying to find hamming string
https://en.wikipedia.org/wiki/Hamming_distance.
I would like to know what does this expression mean and do val &= val - 1;
I know val+=10-->val=val+10
basically trying to find hamming string
https://en.wikipedia.org/wiki/Hamming_distance.
I would like to know what does this expression mean and do val &= val - 1;
I know val+=10-->val=val+10
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.
val &= val - 1
Does the following :
Assigns the result of the bitwise AND operation between val
and val - 1
to val
I think, the exact intention is asked for.
val &= val - 1;
This removes the right-most, least-significant bit:
val: xxxx1000..000
val - 1: xxxx0111..111
val & (val-1): xxxx0000..000
It typically is used to count (destructively) the number of bits.
The same trick: to get the least significant bit itself, use Integer.lowestOneBit(val):
int lowestOneBit = val & -val;
To understand the latter: -n == ~n + 1
. That is: a negative number in java is twos-complement: the one-complement (~n) of every bit plus one.
It's equivalent to following one, where & is a bitwise AND.
val = val & (val - 1)
&=
is a bitwise AND assignment operator and it works basically how compound operators (+=, -=, etc) work in most programming languages.
val &= val - 1;
is same as val = val & (val - 1);
A simple '&' comparison is done between val and val - 1 and the result becomes the value of val
.
Check this link for knowledge on more operators in C as well as how to use them. Merry coding!