Jump to: navigation, search

shouldn't it be:

return x ^ (~(~0U << n) << (p + 1 - n));

--FranklinHyde 13:18, 20 March 2008 (UTC)

What makes you say than? p is the position, so having generated the correct size mask you need to shift it the number of bits specified by p. Now that I have fixed the test driver try running it with Gregory's function and your proposed replacement. --Flash Gordon 21:23, 21 March 2008 (UTC)

I agree with FranklinHyde that the solution should be changed.

For example, if we want to invert 3 bits starting at position 4 in decimal 93: invert (93, 5, 3)

93 = 0101 1101 The answer we should get is 101, because we invert:

  vv v  
0101 1101 = 93

and get:

  vv v
0110 0101 = 101

Running the wiki's solution for invert (x = 93, p = 5, n = 3) we get:

x ^ (~(~0U << n) << p);

0101 1101 ^ (~(1111 1111 << 3) << 5)

0101 1101 ^ (~(1111 1000) << 5)

0101 1101 ^ (0000 0111 << 5)

0101 1101 ^ 1110 0000

   0101 1101
^  1110 0000
------------
   1011 1101 = 189

If on the other hand, we shift the mask left by (p+1-n) instead of p, we get:

x ^ (~(~0U << n) << (p+1-n));

0101 1101 ^ (~(1111 1111 << 3) << (5+1-3))

0101 1101 ^ (~(1111 1000) << 3)

0101 1101 ^ (0000 0111 << 3)

0101 1101 ^ 0011 1000

   0101 1101
^  0011 1000
------------
   0110 0101 = 101

This is the answer we were looking for.

--Forest 00:09, 26 March 2011 (UTC)

Personal tools