Commit patch to not break on spaces.
[bowtie.git] / endian_swap.h
1 #ifndef ENDIAN_SWAP_H
2 #define ENDIAN_SWAP_H
3
4 #include <stdint.h>
5 #include <inttypes.h>
6
7 /**
8  * Return true iff the machine running this program is big-endian.
9  */
10 static inline bool currentlyBigEndian() {
11         static uint8_t endianCheck[] = {1, 0, 0, 0};
12         return *((uint32_t*)endianCheck) != 1;
13 }
14
15 /**
16  * Return copy of uint32_t argument with byte order reversed.
17  */
18 static inline uint32_t endianSwapU32(uint32_t u) {
19         uint32_t tmp = 0;
20         tmp |= ((u >> 24) & (0xff <<  0));
21         tmp |= ((u >>  8) & (0xff <<  8));
22         tmp |= ((u <<  8) & (0xff << 16));
23         tmp |= ((u << 24) & (0xff << 24));
24         return tmp;
25 }
26
27 /**
28  * Return copy of uint64_t argument with byte order reversed.
29  */
30 static inline uint64_t endianSwapU64(uint64_t u) {
31         uint64_t tmp = 0;
32         tmp |= ((u >> 56) & (0xffull <<  0));
33         tmp |= ((u >> 40) & (0xffull <<  8));
34         tmp |= ((u >> 24) & (0xffull << 16));
35         tmp |= ((u >>  8) & (0xffull << 24));
36         tmp |= ((u <<  8) & (0xffull << 32));
37         tmp |= ((u << 24) & (0xffull << 40));
38         tmp |= ((u << 40) & (0xffull << 48));
39         tmp |= ((u << 56) & (0xffull << 56));
40         return tmp;
41 }
42
43
44 /**
45  * Return copy of int32_t argument with byte order reversed.
46  */
47 static inline int32_t endianSwapI32(int32_t i) {
48         int32_t tmp = 0;
49         tmp |= ((i >> 24) & (0xff <<  0));
50         tmp |= ((i >>  8) & (0xff <<  8));
51         tmp |= ((i <<  8) & (0xff << 16));
52         tmp |= ((i << 24) & (0xff << 24));
53         return tmp;
54 }
55
56 /**
57  * Convert uint32_t argument to the specified endianness.  It's assumed
58  * that u currently has the endianness of the current machine.
59  */
60 static inline uint32_t endianizeU32(uint32_t u, bool toBig) {
61         if(toBig == currentlyBigEndian()) {
62                 return u;
63         }
64         return endianSwapU32(u);
65 }
66
67 /**
68  * Convert int32_t argument to the specified endianness.  It's assumed
69  * that u currently has the endianness of the current machine.
70  */
71 static inline int32_t endianizeI32(int32_t i, bool toBig) {
72         if(toBig == currentlyBigEndian()) {
73                 return i;
74         }
75         return endianSwapI32(i);
76 }
77
78 #endif