TransWikia.com

What is n= n ^1U<<i?

Stack Overflow Asked by akshayroy on November 10, 2021

The problem I am facing here is to understand the change in the value of n in each iteration of the loop.
If you explain it by taking 2-3 iteration that will be awesome.
correction -return value should be of 32 bit ….which is altering all bits 0->1 ans 1->0 .

long fun(long n)
{
    for(int i = 0; i < 32; i++)
        n = n ^ 1U << i;
    return n;
}   

2 Answers

It will flip the lower 32 bits in n. That total effect would be the same as just doing n ^= 0xFFFF.

In your code, n is long. If you're on a 32-bit compiler, then it'll have 32 bits, but it could be longer on other compilers.

If you unroll the loop, you get something like this:

n = n ^ 1U << 0;
n = n ^ 1U << 1;
n = n ^ 1U << 2;
...

Since << has higher precedence than ^, that will resolve to this:

n = n ^ 1;
n = n ^ 2;
n = n ^ 4;
...

The end effect is that it flips 32-bits of n, one bit at a time.

Answered by Hines77 on November 10, 2021

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 a long, but the code iterates i through only 32 bits. It flips the low 32 bits in n, leaving high bits, if any, unaltered.
If long is 32 bits, then n = n ^ 1U << i is implementation-defined in some cases since the ^ of a long with an unsigned int will result in an unsigned long, and, if the resulting value cannot be represented in a long, 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.

Answered by Yunnosch on November 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP