2318afdbb8b9d4fc636751c1ec327b5f65baf59a
[libav.git] / bswap.h
1 #ifndef __BSWAP_H__
2 #define __BSWAP_H__
3
4 #ifdef HAVE_CONFIG_H
5 #include "config.h"
6 #endif
7
8 #ifdef HAVE_BYTESWAP_H
9 #include <byteswap.h>
10 #else
11
12 #include <inttypes.h>
13
14 #ifdef ARCH_X86
15 inline static unsigned short ByteSwap16(unsigned short x)
16 {
17 __asm("xchgb %b0,%h0" :
18 "=q" (x) :
19 "0" (x));
20 return x;
21 }
22 #define bswap_16(x) ByteSwap16(x)
23
24 inline static unsigned int ByteSwap32(unsigned int x)
25 {
26 #if __CPU__ > 386
27 __asm("bswap %0":
28 "=r" (x) :
29 #else
30 __asm("xchgb %b0,%h0\n"
31 " rorl $16,%0\n"
32 " xchgb %b0,%h0":
33 "=q" (x) :
34 #endif
35 "0" (x));
36 return x;
37 }
38 #define bswap_32(x) ByteSwap32(x)
39
40 inline static unsigned long long int ByteSwap64(unsigned long long int x)
41 {
42 register union { __extension__ unsigned long long int __ll;
43 unsigned long int __l[2]; } __x;
44 asm("xchgl %0,%1":
45 "=r"(__x.__l[0]),"=r"(__x.__l[1]):
46 "0"(bswap_32((unsigned long)x)),"1"(bswap_32((unsigned long)(x>>32))));
47 return __x.__ll;
48 }
49 #define bswap_64(x) ByteSwap64(x)
50
51 #else
52
53 #define bswap_16(x) (((x) & 0x00ff) << 8 | ((x) & 0xff00) >> 8)
54
55
56 // code from bits/byteswap.h (C) 1997, 1998 Free Software Foundation, Inc.
57 #define bswap_32(x) \
58 ((((x) & 0xff000000) >> 24) | (((x) & 0x00ff0000) >> 8) | \
59 (((x) & 0x0000ff00) << 8) | (((x) & 0x000000ff) << 24))
60
61 #define bswap_64(x) \
62 (__extension__ \
63 ({ union { __extension__ unsigned long long int __ll; \
64 unsigned long int __l[2]; } __w, __r; \
65 __w.__ll = (x); \
66 __r.__l[0] = bswap_32 (__w.__l[1]); \
67 __r.__l[1] = bswap_32 (__w.__l[0]); \
68 __r.__ll; }))
69 #endif /* !ARCH_X86 */
70
71 #endif /* !HAVE_BYTESWAP_H */
72
73 // be2me ... BigEndian to MachineEndian
74 // le2me ... LittleEndian to MachineEndian
75
76 #ifdef WORDS_BIGENDIAN
77 #define be2me_16(x) (x)
78 #define be2me_32(x) (x)
79 #define be2me_64(x) (x)
80 #define le2me_16(x) bswap_16(x)
81 #define le2me_32(x) bswap_32(x)
82 #define le2me_64(x) bswap_64(x)
83 #else
84 #define be2me_16(x) bswap_16(x)
85 #define be2me_32(x) bswap_32(x)
86 #define be2me_64(x) bswap_64(x)
87 #define le2me_16(x) (x)
88 #define le2me_32(x) (x)
89 #define le2me_64(x) (x)
90 #endif
91
92 #endif