]> wimlib.net Git - wimlib/blob - src/endianness.h
NTFS capture (IN PROGRESS)
[wimlib] / src / endianness.h
1 #ifndef _WIMLIB_ENDIANNESS_H
2 #define _WIMLIB_ENDIANNESS_H
3
4
5 #include "config.h"
6 #include <inttypes.h>
7
8 /* Changes the endianness of a 32-bit value. */
9 static inline uint32_t bswap32(uint32_t n)
10 {
11 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)
12         return __builtin_bswap32(n);
13 #else
14         return (n << 24) | ((n & 0xff00) << 8) | ((n & 0xff0000) >> 8) | 
15                                                         (n >> 24);
16 #endif
17 }
18
19 #ifdef WORDS_BIGENDIAN
20
21 /* Big endian. */
22
23 /* Changes the endianness of a 16-bit value. */
24 static inline uint16_t bswap16(uint16_t n)
25 {
26         return (n << 8) | (n >> 8);
27 }
28
29
30 /* Changes the endianness of a 64-bit value. */
31 static inline uint64_t bswap64(uint64_t n)
32 {
33 #ifdef __GNUC__
34         return __builtin_bswap64(n);
35 #else
36         return (n << 56) | ((n & 0xff00) << 40) | ((n & 0xff0000) << 24) | 
37                         ((n & 0xff000000) << 8) | ((n & 0xff00000000) >> 8) | 
38                         ((n & 0xff0000000000) >> 24) | 
39                         ((n & 0xff000000000000) >> 40) | (n >> 56);
40 #endif
41 }
42
43 /* Not in place */
44 #define to_le16(n) bswap16(n)
45 #define to_le32(n) bswap32(n)
46 #define to_le64(n) bswap64(n)
47 #define to_be16(n) (n)
48 #define to_be32(n) (n)
49 #define to_be64(n) (n)
50
51 #define le16_to_cpu(n) bswap16(n)
52 #define le32_to_cpu(n) bswap32(n)
53 #define le64_to_cpu(n) bswap64(n)
54
55 /* In place */
56 #define TO_LE16(n) ((n) = to_le16(n))
57 #define TO_LE32(n) ((n) = to_le32(n))
58 #define TO_LE64(n) ((n) = to_le64(n))
59
60 static inline void array_to_le16(uint16_t *p, uint64_t n)
61 {
62         while (n--)
63                 *p++ = to_le16(*p);
64 }
65 static inline void array_to_le32(uint32_t *p, uint64_t n)
66 {
67         while (n--)
68                 *p++ = to_le32(*p);
69 }
70 static inline void array_to_le64(uint64_t *p, uint64_t n)
71 {
72         while (n--)
73                 *p++ = to_le64(*p);
74 }
75
76 #else
77
78 /* Little endian. */
79
80 /* Not in place */
81 #define to_le16(n) (n)
82 #define to_le32(n) (n)
83 #define to_le64(n) (n)
84
85 #define le16_to_cpu(n) (n)
86 #define le32_to_cpu(n) (n)
87 #define le64_to_cpu(n) (n)
88
89 #define to_be16(n) (bswap16(n))
90 #define to_be32(n) (bswap32(n))
91 #define to_be64(n) (bswap64(n))
92
93 /* In place */
94 #define TO_LE16(n)
95 #define TO_LE32(n)
96 #define TO_LE64(n)
97
98 #define array_to_le16(p, n)
99 #define array_to_le32(p, n)
100 #define array_to_le64(p, n)
101
102 #endif
103
104
105 #endif /* _WIMLIB_ENDIANNESS_H */