home *** CD-ROM | disk | FTP | other *** search
/ Media Share 13 / mediashare_13.zip / mediashare_13 / ZIPPED / PROGRAM / SNIP9404.ZIP / MEMREV.C < prev    next >
C/C++ Source or Header  |  1994-04-03  |  1KB  |  53 lines

  1. /*
  2. **  Public domain demo by Ray Gardner, 7 dec 88
  3. **
  4. **  Here's an old programming trick that (I bet) will be new to at least a
  5. **  few of you out there, even some "old hands".  I don't remember where I
  6. **  saw this; it might have been Jon Bentley's "Programming Pearls" column in
  7. **  Communications of the ACM.
  8. **
  9. **  Have you ever wanted to exchange two adjacent areas of storage which
  10. **  might be of two different lengths?  There are some tricky and complicated
  11. **  "efficient" methods to do this without using a lot of extra temporary
  12. **  storage.  But there is also an old and simple way: Assume that the buffer
  13. **  looks like this:
  14. **
  15. **     |...... head .......|.................. tail .................|
  16. **
  17. **  You reverse the head, reverse the tail, then reverse the entire buffer.
  18. **  That's all there is to it.  It will leave you with:
  19. **
  20. **     |.................. tail .................|...... head .......|
  21. **
  22. **  Here's code:
  23. */
  24.  
  25. #include <stdlib.h>
  26.  
  27. /*
  28. **  reverse "count" bytes starting at "buf"
  29. */
  30.  
  31. void memrev(char  *buf, size_t count)
  32. {
  33.       char *r;
  34.  
  35.       for (r = buf + count - 1; buf < r; buf++, r--)
  36.       {
  37.             *buf ^= *r;
  38.             *r   ^= *buf;
  39.             *buf ^= *r;
  40.       }
  41. }
  42.  
  43. /*
  44. **  swap "head" bytes with "tail" bytes at "buf"
  45. */
  46.  
  47. void aswap(char  *buf, size_t head, size_t tail)
  48. {
  49.       memrev(buf, head);
  50.       memrev(buf + head, tail);
  51.       memrev(buf, head + tail);
  52. }
  53.