1 /*
2  * Copyright (c) 2010 Espressif System
3  */
4 
5 #ifndef BYTESWAP_H
6 #define BYTESWAP_H
7 
8 #include <machine/endian.h>
9 
10 /* Swap bytes in 16 bit value.  */
11 #ifndef __bswap_16
12 #ifdef __GNUC__
13 # define __bswap_16(x) \
14     (__extension__							      \
15      ({ unsigned short int __bsx = (x);					      \
16         ((((__bsx) >> 8) & 0xff) | (((__bsx) & 0xff) << 8)); }))
17 #else
18 static INLINE unsigned short int
__bswap_16(unsigned short int __bsx)19 __bswap_16 (unsigned short int __bsx)
20 {
21   return ((((__bsx) >> 8) & 0xff) | (((__bsx) & 0xff) << 8));
22 }
23 #endif
24 #endif // __bswap_16
25 
26 /* Swap bytes in 32 bit value.  */
27 #ifndef __bswap_32
28 #ifdef __GNUC__
29 # define __bswap_32(x) \
30     (__extension__							      \
31      ({ unsigned int __bsx = (x);					      \
32         ((((__bsx) & 0xff000000) >> 24) | (((__bsx) & 0x00ff0000) >>  8) |    \
33 	 (((__bsx) & 0x0000ff00) <<  8) | (((__bsx) & 0x000000ff) << 24)); }))
34 #else
35 static INLINE unsigned int
__bswap_32(unsigned int __bsx)36 __bswap_32 (unsigned int __bsx)
37 {
38   return ((((__bsx) & 0xff000000) >> 24) | (((__bsx) & 0x00ff0000) >>  8) |
39 	  (((__bsx) & 0x0000ff00) <<  8) | (((__bsx) & 0x000000ff) << 24));
40 }
41 #endif
42 #endif // __bswap_32
43 
44 #ifndef __bswap_64
45 #if defined __GNUC__ && __GNUC__ >= 2
46 /* Swap bytes in 64 bit value.  */
47 # define __bswap_constant_64(x) \
48      ((((x) & 0xff00000000000000ull) >> 56)				      \
49       | (((x) & 0x00ff000000000000ull) >> 40)				      \
50       | (((x) & 0x0000ff0000000000ull) >> 24)				      \
51       | (((x) & 0x000000ff00000000ull) >> 8)				      \
52       | (((x) & 0x00000000ff000000ull) << 8)				      \
53       | (((x) & 0x0000000000ff0000ull) << 24)				      \
54       | (((x) & 0x000000000000ff00ull) << 40)				      \
55       | (((x) & 0x00000000000000ffull) << 56))
56 
57 # define __bswap_64(x) \
58      (__extension__							      \
59       ({ union { __extension__ unsigned long long int __ll;		      \
60 		 unsigned int __l[2]; } __w, __r;			      \
61          if (__builtin_constant_p (x))					      \
62 	   __r.__ll = __bswap_constant_64 (x);				      \
63 	 else								      \
64 	   {								      \
65 	     __w.__ll = (x);						      \
66 	     __r.__l[0] = __bswap_32 (__w.__l[1]);			      \
67 	     __r.__l[1] = __bswap_32 (__w.__l[0]);			      \
68 	   }								      \
69 	 __r.__ll; }))
70 #endif
71 #endif // __bswap_64
72 
73 #endif /* BYTESWAP_H */
74