1 // Copyright (c) 2014-2016 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_COMPAT_BYTESWAP_H
6 #define BITCOIN_COMPAT_BYTESWAP_H
8 #if defined(HAVE_CONFIG_H)
9 #include <config/bitcoin-config.h>
14 #if defined(HAVE_BYTESWAP_H)
18 #if defined(__APPLE__)
20 #if !defined(bswap_16)
22 // Mac OS X / Darwin features; we include a check for bswap_16 because if it is already defined, protobuf has
23 // defined these macros for us already; if it isn't, we do it ourselves. In either case, we get the exact same
24 // result regardless which path was taken
25 #include <libkern/OSByteOrder.h>
26 #define bswap_16(x) OSSwapInt16(x)
27 #define bswap_32(x) OSSwapInt32(x)
28 #define bswap_64(x) OSSwapInt64(x)
30 #endif // !defined(bswap_16)
33 // Non-Mac OS X / non-Darwin
35 #if HAVE_DECL_BSWAP_16 == 0
36 inline uint16_t bswap_16(uint16_t x
)
38 return (x
>> 8) | (x
<< 8);
40 #endif // HAVE_DECL_BSWAP16 == 0
42 #if HAVE_DECL_BSWAP_32 == 0
43 inline uint32_t bswap_32(uint32_t x
)
45 return (((x
& 0xff000000U
) >> 24) | ((x
& 0x00ff0000U
) >> 8) |
46 ((x
& 0x0000ff00U
) << 8) | ((x
& 0x000000ffU
) << 24));
48 #endif // HAVE_DECL_BSWAP32 == 0
50 #if HAVE_DECL_BSWAP_64 == 0
51 inline uint64_t bswap_64(uint64_t x
)
53 return (((x
& 0xff00000000000000ull
) >> 56)
54 | ((x
& 0x00ff000000000000ull
) >> 40)
55 | ((x
& 0x0000ff0000000000ull
) >> 24)
56 | ((x
& 0x000000ff00000000ull
) >> 8)
57 | ((x
& 0x00000000ff000000ull
) << 8)
58 | ((x
& 0x0000000000ff0000ull
) << 24)
59 | ((x
& 0x000000000000ff00ull
) << 40)
60 | ((x
& 0x00000000000000ffull
) << 56));
62 #endif // HAVE_DECL_BSWAP64 == 0
64 #endif // defined(__APPLE__)
66 #endif // BITCOIN_COMPAT_BYTESWAP_H