IBR-DTNSuite  0.12
Endianess.h
Go to the documentation of this file.
1 /*
2  * endian.c
3  *
4  * Copyright (C) 2013 IBR, TU Braunschweig
5  *
6  * Written-by: Johannes Morgenroth <morgenroth@ibr.cs.tu-bs.de>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21 
22 // DO NOT INCLUDE THIS FILE IN A HEADER FILE!
23 
24 #include <stdint.h>
25 
26 #ifndef ENDIANESS_H_
27 #define ENDIANESS_H_
28 
29 namespace dtn
30 {
31  namespace data
32  {
33  uint16_t bswap16(uint16_t x);
34  uint32_t bswap32(uint32_t x);
35  uint64_t bswap64(uint64_t x);
36  }
37 }
38 
39 #ifdef HAVE_GLIB
40  // GLIB provides optimized macros for endianess conversion
41  // we prefer to use them
42  #include <glib.h>
43 #else
44  // include endianess headers
45  #if HAVE_ENDIAN_H
46  // include standard POSIX endian.h
47  #include <endian.h>
48  #elif HAVE_MACHINE_ENDIAN_H
49  // include BSD endian.h
50  #include <machine/endian.h>
51  #elif __WIN32__
52  // windows has no endian header, but
53  // provides byte swapping in the winsock2 API
54  #include <winsock2.h>
55  #define BYTE_ORDER __BYTE_ORDER
56  #define LITTLE_ENDIAN __LITTLE_ENDIAN
57  #endif
58 
59  // check if system byte order is network order
60  #if BYTE_ORDER == LITTLE_ENDIAN
61  // if POSIX htobe16 is available use it
62  #ifdef htobe16
63  #define GUINT16_TO_BE(x) htobe16(x)
64  #else
65  #define GUINT16_TO_BE(x) dtn::data::bswap16(x)
66  #endif
67 
68  // if POSIX htobe32 is available use it
69  #ifdef htobe32
70  #define GUINT32_TO_BE(x) htobe32(x)
71  #else
72  #define GUINT32_TO_BE(x) dtn::data::bswap32(x)
73  #endif
74 
75  // if POSIX htobe64 is available use it
76  #ifdef htobe64
77  #define GUINT64_TO_BE(x) htobe64(x)
78  #else
79  #define GUINT64_TO_BE(x) dtn::data::bswap64(x)
80  #endif
81  #else
82  // system byte order is equal to network byte order
83  // generate dummy macros
84  #define GUINT16_TO_BE(x) (x)
85  #define GUINT32_TO_BE(x) (x)
86  #define GUINT64_TO_BE(x) (x)
87  #endif
88 #endif
89 
90 #endif /* ENDIANESS_H_ */