home *** CD-ROM | disk | FTP | other *** search
/ Programmer 7500 / MAX_PROGRAMMERS.iso / INFO / TIFF / TFTOOL.ZIP / SWAP.C < prev    next >
Encoding:
C/C++ Source or Header  |  1988-11-02  |  1.9 KB  |  75 lines

  1. /* swap.c - routines to swap (reverse) words and double words
  2.  */
  3. #include "aldtypes.h"
  4. #include "swap.h"
  5.  
  6. /* swap bytes within words -- overlapping arrays are handled properly
  7.  */
  8. void swab (lpSrc, lpDst, nbytes)
  9. register LPSTR    lpSrc, lpDst;    /* assumed to be word-aligned */
  10. WORD              nbytes;            /* assumed to be even */
  11. {
  12.         register WORD words;
  13.         union {
  14.             char c[2];
  15.             WORD w;
  16.         } wrd;
  17.  
  18.         words = nbytes/2;
  19.  
  20.         if (lpDst <= lpSrc || lpDst >= lpSrc + nbytes) {
  21.             for (; words--; lpSrc += 2) {
  22.                 wrd.w = *(WORD FAR *)lpSrc;
  23.                 *lpDst++ = *(LPSTR)(wrd.c + 1);    /* W2 doesn't like wrd.c[1] */
  24.                 *lpDst++ = *(LPSTR)(wrd.c);
  25.             }
  26.         }
  27.         else {        /* we'll have to go backward */
  28.             lpSrc += nbytes - sizeof(WORD);
  29.             lpDst += nbytes - 1;
  30.             for (; words--; lpSrc -= 2) {
  31.                 wrd.w = *(WORD FAR *)lpSrc;
  32.                 *lpDst-- = *(LPSTR)(wrd.c);
  33.                 *lpDst-- = *(LPSTR)(wrd.c + 1);
  34.             }
  35.         }
  36. }
  37.  
  38. /* swap words -- overlapping ranges are handled properly
  39.  *
  40.  * actually, does a 4-byte reversal
  41.  */
  42. void swaw (lpSrc, lpDst, nbytes)
  43. register LPSTR    lpSrc, lpDst;    /* assumed to be word-aligned */
  44. WORD              nbytes;            /* assumed to be multiple of 4 */
  45. {
  46.         register WORD dwords;
  47.         union {
  48.             char c[4];
  49.             DWORD dw;
  50.         } dwrd;
  51.  
  52.         dwords = nbytes/4;
  53.  
  54.         if (lpDst <= lpSrc || lpDst >= lpSrc + nbytes) {
  55.             for (; dwords--; lpSrc += 4) {
  56.                 dwrd.dw = *(DWORD FAR *)lpSrc;
  57.                 *lpDst++ = *(LPSTR)(dwrd.c + 3);
  58.                 *lpDst++ = *(LPSTR)(dwrd.c + 2);
  59.                 *lpDst++ = *(LPSTR)(dwrd.c + 1);
  60.                 *lpDst++ = *(LPSTR)(dwrd.c);
  61.             }
  62.         }
  63.         else {        /* we'll have to go backward */
  64.             lpSrc += nbytes - sizeof(DWORD);
  65.             lpDst += nbytes - 1;
  66.             for (; dwords--; lpSrc -= 4) {
  67.                 dwrd.dw = *(DWORD FAR *)lpSrc;
  68.                 *lpDst-- = *(LPSTR)(dwrd.c);
  69.                 *lpDst-- = *(LPSTR)(dwrd.c + 1);
  70.                 *lpDst-- = *(LPSTR)(dwrd.c + 2);
  71.                 *lpDst-- = *(LPSTR)(dwrd.c + 3);
  72.             }
  73.         }
  74. }
  75.