Re^2: Bit Switching - How?

Frank Wales frank at zen.co.uk
Mon Apr 10 20:48:08 AEST 1989


In article <1574 at lznv.ATT.COM> jlw at lznv.ATT.COM (J.L.WOOD) writes:
>> sl at van-bc.UUCP (pri=-10 Stuart Lynne) writes:
>> \For fast generic swapping I use:
>> 
>> \#define	swap(a,b) {a^=b;b^=a;a^= b;}
>> 
>
>Also be careful how you use this algorithm if you are using pointers.
>I once used this method in a sorting routine as my basic exchange and
>got badly burned.
>
>If a and b point to the same location, you get zero as in 0, nada, goose egg.

Well, this surprised me, since blurfl^blurfl does give 0, but blurfl^0
gives blurfl again, so you should get it back, unless some pretty funky
pointer-to-int conversion is taking place.  I tried the following
myself (admittedly on a fairly well-behaved machine from HP),

#include<stdio.h>
#define ptr_swap(a,b)  (a=(void *)((unsigned long)a^(unsigned long)b),\
			b=(void *)((unsigned long)a^(unsigned long)b),\
			a=(void *)((unsigned long)a^(unsigned long)b))

main(argc,argv)
char *argv[];
{
  char *a=argv[0],*b=argv[0];

  (void)printf("a=%lx, b=%lx\n",(unsigned long)a,(unsigned long)b);
  ptr_swap(a,b);
  (void)printf("a=%lx, b=%lx\n",(unsigned long)a,(unsigned long)b);
  return 0;
}

and got:

a=68023000, b=68023000
a=68023000, b=68023000

I'd be interested to find out the machine on which this XOR trick
fails to swap integral values correctly.  [I hardly ever use it, but
I'd still expect it to work.]  Or is there some portability problem
lurking here that my Monday morning mind has missed?
--
Frank Wales, Systems Manager,        [frank at zen.co.uk<->mcvax!zen.co.uk!frank]
Zengrange Ltd., Greenfield Rd., Leeds, ENGLAND, LS9 8DB. (+44) 532 489048 x217 



More information about the Comp.unix.questions mailing list