home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / MEMREV.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  56 lines

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