My solution just tests bit i and either sets or clears bit j based on the result. Then it does the same testing bit j and setting or clearing bit i.
There are many other possibilities. It would be slick if C shift operators accepted negative shift values. But they don't. Instead you could shift the bits down to position 0 then shift them back up to their swapped positions and substitute in the input value. This one has a spooky symmetry. unsigned swap(unsigned x, int i, int j) { unsigned bit_i = (1u << i) & x; unsigned bit_j = (1u << j) & x; return (x ^ bit_i ^ bit_j) | (bit_i >> i << j) | (bit_j >> j << i); } On Sep 13, 9:07 pm, Dave <dave_and_da...@juno.com> wrote: > Replying to myself: I should proofread better _before_ I post. Sorry, > but the explanation should say > > ni is bit i of n. nj is bit j of n. n & ~(ni | nj) removes the two > bits, and then they are shifted to the exchanged positions and or'd > in. > > Dave > > On Sep 13, 2:04 pm, Dave <dave_and_da...@juno.com> wrote: > > > > > @Kumar: How about this: > > > int exchange2bits(int n, int i, int j) // exchange bits i and j of n. > > { > > int ni, nj; > > ni = n & (1 << i); > > nj = n & (1 << j); > > return n & ~(ni | nj) | ((ni >> i) << j) | ((nj >> j) << i); > > > } > > > ni is bit i of n. nj is bit j of n. n & (ni | nj) removes the two > > bits, and then they are shifted to the exchanged positions and or'd > > in. > > > Dave > > > On Sep 13, 1:50 pm, kumar raja <rajkumar.cs...@gmail.com> wrote: > > > > Suppose a number 'n' is given and two bits positions i,j present in > > > binary > > > representation of n . > > > > Then how to exchange the contents of the two bits i and j. > > > > E.g. n= 13 > > > its binary representation is 0000 1101 (just for now consider 8 bit > > > number) > > > > i= 2,j=6 > > > > o/p : 0100 1001 = 73 > > > > please suggest some effective way to do this... > > > > -- > > > Regards > > > Kumar Raja > > > M.Tech(SIT) > > > IIT Kharagpur, > > > 10it60...@iitkgp.ac.in > > > 7797137043. > > > 09491690115.- Hide quoted text - > > > - Show quoted text -- Hide quoted text - > > - Show quoted text - -- You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group. To post to this group, send email to algogeeks@googlegroups.com. To unsubscribe from this group, send email to algogeeks+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/algogeeks?hl=en.