reversing a mask

Steven M. Haflich smh at mit-eddie.UUCP
Sun Nov 25 23:42:43 AEST 1984


Much more space-efficient and only slightly slower is the following:

  char revbytes[256] = { 0x00, 0x80, 0x40, 0xc0, ... , 0x7f, 0xff };
  #define reverse(v) ((revbytes((v)&0xff)<<8)|revbytes(((v)>>8)&0xff))

That's the general idea.  This is not perfectly portable, but then,
neither was the original problem.  Depending on particular C
implementation, various dodges may be necessary to prevent the infamous
char sign extension problem: either by declaring revbytes to be
"unsigned char", or else by anding each mention of revbytes with 0xff.
Also, note that the argument gets evaluated twice, but this could be
corrected if necessary.

Steve Haflich



More information about the Comp.lang.c mailing list