]> wimlib.net Git - wimlib/blob - src/endianness.h
pre-resolve streams (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 /* In place */
52 #define TO_LE16(n) ((n) = to_le16(n))
53 #define TO_LE32(n) ((n) = to_le32(n))
54 #define TO_LE64(n) ((n) = to_le64(n))
55
56 static inline void array_to_le16(uint16_t *p, uint64_t n)
57 {
58         while (n--)
59                 *p++ = to_le16(*p);
60 }
61 static inline void array_to_le32(uint32_t *p, uint64_t n)
62 {
63         while (n--)
64                 *p++ = to_le32(*p);
65 }
66 static inline void array_to_le64(uint64_t *p, uint64_t n)
67 {
68         while (n--)
69                 *p++ = to_le64(*p);
70 }
71
72 #else
73
74 /* Little endian. */
75
76 /* Not in place */
77 #define to_le16(n) (n)
78 #define to_le32(n) (n)
79 #define to_le64(n) (n)
80
81 #define to_be16(n) (bswap16(n))
82 #define to_be32(n) (bswap32(n))
83 #define to_be64(n) (bswap64(n))
84
85 /* In place */
86 #define TO_LE16(n)
87 #define TO_LE32(n)
88 #define TO_LE64(n)
89
90 #define array_to_le16(p, n)
91 #define array_to_le32(p, n)
92 #define array_to_le64(p, n)
93
94 #endif
95
96
97 #endif /* _WIMLIB_ENDIANNESS_H */