ROFL-pipeline  v0.6.0dev
endianness.h
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 #ifndef __ENDIANNESS_H__
6 #define __ENDIANNESS_H__
7 
8 #include "rofl_config.h"
9 #include <stdint.h>
10 
11 /*
12 * Add a macro implementation for htonb and ntohb
13 */
14 
15 #if defined(BIG_ENDIAN_DETECTED)
16  //Host -> Network
17  #define HTONB16(x) x
18  #define HTONB32(x) x
19  #define HTONB64(x) x
20 
21  //Network -> Host
22  #define NTOHB16(x) x
23  #define NTOHB32(x) x
24  #define NTOHB64(x) x
25 
26  //
27  // Conditional byte swappers. Convienience wrapper
28  //
29  #define COND_NTOHB16(nbo, x) x
30  #define COND_NTOHB32(nbo, x) x
31  #define COND_NTOHB64(nbo, x) x
32 #elif defined(LITTLE_ENDIAN_DETECTED)
33  #if defined(BYTESWAP_HEADER_DETECTED)
34  #include <byteswap.h>
35 
36  //Host -> Network
37  #define HTONB16(x) __bswap_16(x)
38  #define HTONB32(x) __bswap_32(x)
39  #define HTONB64(x) __bswap_64(x)
40 
41  //Network -> Host
42  #define NTOHB16(x) __bswap_16(x)
43  #define NTOHB32(x) __bswap_32(x)
44  #define NTOHB64(x) __bswap_64(x)
45  #else
46  //Host -> Network
47  #define HTONB16(x) ( (((x) >> 8) & 0x00FF) | (((x) << 8) & 0xFF00) )
48  #define HTONB32(x) \
49  ( (((x) >> 24) & 0x000000FF) | (((x) >> 8) & 0x0000FF00) | \
50  (((x) << 8) & 0x00FF0000) | (((x) << 24) & 0xFF000000) )
51 
52 
53  #define HTONB64(x) \
54  ( (((x) >> 56) & 0x00000000000000FF) | (((x) >> 40) & 0x000000000000FF00) | \
55  (((x) >> 24) & 0x0000000000FF0000) | (((x) >> 8) & 0x00000000FF000000) | \
56  (((x) << 8) & 0x000000FF00000000) | (((x) << 24) & 0x0000FF0000000000) | \
57  (((x) << 40) & 0x00FF000000000000) | (((x) << 56) & 0xFF00000000000000) )
58 
59  //Network -> Host
60  #define NTOHB16(x) HTONB16(x)
61  #define NTOHB32(x) HTONB32(x)
62  #define NTOHB64(x) HTONB64(x)
63 
64  #endif
65 
66  //
67  // Conditional byte swappers. Convienience wrapper
68  //
69  #define COND_NTOHB16(nbo, x) ( (nbo)? x : NTOHB16(x) )
70  #define COND_NTOHB32(nbo, x) ( (nbo)? x : NTOHB32(x) )
71  #define COND_NTOHB64(nbo, x) ( (nbo)? x : NTOHB64(x) )
72 #else
73  #error Unsupported endianness
74 #endif //endianness check
75 
76 #endif //__ENDIANNESS_H__