1 /*
2  *  Copyright 2006  Serge van den Boom <svdb@stack.nl>
3  *
4  *  This program is free software; you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation; either version 2 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License
15  *  along with this program; if not, write to the Free Software
16  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18 
19 // Routines for changing the endianness of values.
20 // I'm not using ntohs() etc. as those would require include files that may
21 // have conflicting definitions. This is a problem on Windows, where these
22 // functions are in winsock2.h, which includes windows.h, which includes
23 // pretty much Microsoft's complete collection of .h files.
24 
25 #ifndef LIBS_NETWORK_BYTESEX_H_
26 #define LIBS_NETWORK_BYTESEX_H_
27 
28 #include "port.h"
29 		// for inline
30 #include "endian_uqm.h"
31 		// for WORDS_BIGENDIAN
32 #include "types.h"
33 
34 static inline uint16
swapBytes16(uint16 x)35 swapBytes16(uint16 x) {
36 	return (x << 8) | (x >> 8);
37 }
38 
39 static inline uint32
swapBytes32(uint32 x)40 swapBytes32(uint32 x) {
41 	return (x << 24)
42 			| ((x & 0x0000ff00) << 8)
43 			| ((x & 0x00ff0000) >> 8)
44 			| (x >> 24);
45 }
46 
47 #ifdef WORDS_BIGENDIAN
48 // Already in network order.
49 
50 static inline uint16
hton16(uint16 x)51 hton16(uint16 x) {
52 	return x;
53 }
54 
55 static inline uint32
hton32(uint32 x)56 hton32(uint32 x) {
57 	return x;
58 }
59 
60 static inline uint16
ntoh16(uint16 x)61 ntoh16(uint16 x) {
62 	return x;
63 }
64 
65 static inline uint32
ntoh32(uint32 x)66 ntoh32(uint32 x) {
67 	return x;
68 }
69 
70 #else  /* !defined(WORDS_BIGENDIAN) */
71 // Need to swap bytes
72 
73 static inline uint16
hton16(uint16 x)74 hton16(uint16 x) {
75 	return swapBytes16(x);
76 }
77 
78 static inline uint32
hton32(uint32 x)79 hton32(uint32 x) {
80 	return swapBytes32(x);
81 }
82 
83 static inline uint16
ntoh16(uint16 x)84 ntoh16(uint16 x) {
85 	return swapBytes16(x);
86 }
87 
88 static inline uint32
ntoh32(uint32 x)89 ntoh32(uint32 x) {
90 	return swapBytes32(x);
91 }
92 
93 #endif  /* defined(WORDS_BIGENDIAN) */
94 
95 #endif  /* LIBS_NETWORK_BYTESEX_H_ */
96 
97