1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This header defines cross-platform ByteSwap() implementations for 16, 32 and
6 // 64-bit values, and NetToHostXX() / HostToNextXX() functions equivalent to
7 // the traditional ntohX() and htonX() functions.
8 // Use the functions defined here rather than using the platform-specific
11 #ifndef BASE_SYS_BYTEORDER_H_
12 #define BASE_SYS_BYTEORDER_H_
14 #include "base/basictypes.h"
15 #include "build/build_config.h"
20 #include <arpa/inet.h>
23 // Include headers to provide byteswap for all platforms.
24 #if defined(COMPILER_MSVC)
26 #elif defined(OS_MACOSX)
27 #include <libkern/OSByteOrder.h>
28 #elif defined(OS_OPENBSD)
29 #include <sys/endian.h>
37 // Returns a value with all bytes in |x| swapped, i.e. reverses the endianness.
38 inline uint16
ByteSwap(uint16 x
) {
39 #if defined(COMPILER_MSVC)
40 return _byteswap_ushort(x
);
41 #elif defined(OS_MACOSX)
42 return OSSwapInt16(x
);
43 #elif defined(OS_OPENBSD)
49 inline uint32
ByteSwap(uint32 x
) {
50 #if defined(COMPILER_MSVC)
51 return _byteswap_ulong(x
);
52 #elif defined(OS_MACOSX)
53 return OSSwapInt32(x
);
54 #elif defined(OS_OPENBSD)
60 inline uint64
ByteSwap(uint64 x
) {
61 #if defined(COMPILER_MSVC)
62 return _byteswap_uint64(x
);
63 #elif defined(OS_MACOSX)
64 return OSSwapInt64(x
);
65 #elif defined(OS_OPENBSD)
72 // Converts the bytes in |x| from host order (endianness) to little endian, and
73 // returns the result.
74 inline uint16
ByteSwapToLE16(uint16 x
) {
75 #if defined(ARCH_CPU_LITTLE_ENDIAN)
81 inline uint32
ByteSwapToLE32(uint32 x
) {
82 #if defined(ARCH_CPU_LITTLE_ENDIAN)
88 inline uint64
ByteSwapToLE64(uint64 x
) {
89 #if defined(ARCH_CPU_LITTLE_ENDIAN)
96 // Converts the bytes in |x| from network to host order (endianness), and
97 // returns the result.
98 inline uint16
NetToHost16(uint16 x
) {
99 #if defined(ARCH_CPU_LITTLE_ENDIAN)
105 inline uint32
NetToHost32(uint32 x
) {
106 #if defined(ARCH_CPU_LITTLE_ENDIAN)
112 inline uint64
NetToHost64(uint64 x
) {
113 #if defined(ARCH_CPU_LITTLE_ENDIAN)
120 // Converts the bytes in |x| from host to network order (endianness), and
121 // returns the result.
122 inline uint16
HostToNet16(uint16 x
) {
123 #if defined(ARCH_CPU_LITTLE_ENDIAN)
129 inline uint32
HostToNet32(uint32 x
) {
130 #if defined(ARCH_CPU_LITTLE_ENDIAN)
136 inline uint64
HostToNet64(uint64 x
) {
137 #if defined(ARCH_CPU_LITTLE_ENDIAN)
147 #endif // BASE_SYS_BYTEORDER_H_