scorici

swapnib.c

Nov 7th, 2015
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.69 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <limits.h>
  3.  
  4. // works for 8 bits
  5. unsigned swapnib8(unsigned n)
  6. {
  7.    return (n << 4) & 0xFF | n >> 4;
  8. }
  9.  
  10. unsigned swapnib(unsigned n)
  11. {
  12.  
  13.   if (n == 0) return n;
  14.   unsigned lastbyte = swapnib8(n & 0xFF);
  15.   unsigned rest = swapnib(n >> 8) << 8;
  16.   return rest | lastbyte;
  17.   /*
  18.   printf("%x\n", n);
  19.   return n ?  (swapnib(n >> 8) << 8) | swapnib8(n & 0xff) : n;
  20.   */
  21. }
  22.  
  23. unsigned swapnib2(unsigned n)
  24. {
  25.   unsigned r = 0;
  26.   for (unsigned m4 = 0xF; m4; m4 <<= 4) {
  27.     r |= ((n & m4) << 4);
  28.     m4 <<= 4;
  29.     r |= (n & m4) >> 4;
  30.   }
  31.   return r;  
  32. }
  33.  
  34. int main(void)
  35. {
  36.     unsigned n = 0xdeadbeef;
  37.     printf("%x %x\n", n, swapnib(n));
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment