What is n= n ^1U<<i?
i
is counting.
1U << i
is a single unsigned bit (LSB), which gets shifted in each turn by i
to the left, i.e. it scans the bit positions, 0001, 0010, 0100, 1000 (read as binary please).
n = n ^ 1U << i
sets n
to a XOR of n
and the shifted bit. I.e. it XORs n
bit by bit completely.
The result is a completely inverted n
.
Lets look at 4 iterations on the example 13, 1101 in binary.
1101 ^ 0001 is 1100
1100 ^ 0010 is 1110
1110 ^ 0100 is 1010
1010 ^ 1000 is 0010
0010 is 1101 ^ 1111
As Eric Postpischil mentions:
The parameter
n
to the function is along
, but the code iteratesi
through only 32 bits. It flips the low 32 bits inn
, leaving high bits, if any, unaltered.
Iflong
is 32 bits, thenn = n ^ 1U << i
is implementation-defined in some cases since the^
of along
with anunsigned int
will result in anunsigned long
, and, if the resulting value cannot be represented in along
, the result is implementation-defined.
If we assume suitable input of n
, e.g. being representable in the 32-bit wide type, or that the flipping of only lower bits is intentional, then that is not a problem.
Note with this and with Eric's comment, that a long
is implicitly signed, which implies that the quasi MSB is not fully available for value representation (whether 2-complement or 1-complement or sign representation), because half of the range is used for negative values. Toggling it via a XOR then has potentially weird effects.