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>
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)
45 #elif defined(OS_FREEBSD)
51 inline uint32
ByteSwap(uint32 x
) {
52 #if defined(COMPILER_MSVC)
53 return _byteswap_ulong(x
);
54 #elif defined(OS_MACOSX)
55 return OSSwapInt32(x
);
56 #elif defined(OS_OPENBSD)
58 #elif defined(OS_FREEBSD)
64 inline uint64
ByteSwap(uint64 x
) {
65 #if defined(COMPILER_MSVC)
66 return _byteswap_uint64(x
);
67 #elif defined(OS_MACOSX)
68 return OSSwapInt64(x
);
69 #elif defined(OS_OPENBSD)
71 #elif defined(OS_FREEBSD)
78 // Converts the bytes in |x| from host order (endianness) to little endian, and
79 // returns the result.
80 inline uint16
ByteSwapToLE16(uint16 x
) {
81 #if defined(ARCH_CPU_LITTLE_ENDIAN)
87 inline uint32
ByteSwapToLE32(uint32 x
) {
88 #if defined(ARCH_CPU_LITTLE_ENDIAN)
94 inline uint64
ByteSwapToLE64(uint64 x
) {
95 #if defined(ARCH_CPU_LITTLE_ENDIAN)
102 // Converts the bytes in |x| from network to host order (endianness), and
103 // returns the result.
104 inline uint16
NetToHost16(uint16 x
) {
105 #if defined(ARCH_CPU_LITTLE_ENDIAN)
111 inline uint32
NetToHost32(uint32 x
) {
112 #if defined(ARCH_CPU_LITTLE_ENDIAN)
118 inline uint64
NetToHost64(uint64 x
) {
119 #if defined(ARCH_CPU_LITTLE_ENDIAN)
126 // Converts the bytes in |x| from host to network order (endianness), and
127 // returns the result.
128 inline uint16
HostToNet16(uint16 x
) {
129 #if defined(ARCH_CPU_LITTLE_ENDIAN)
135 inline uint32
HostToNet32(uint32 x
) {
136 #if defined(ARCH_CPU_LITTLE_ENDIAN)
142 inline uint64
HostToNet64(uint64 x
) {
143 #if defined(ARCH_CPU_LITTLE_ENDIAN)
153 #endif // BASE_SYS_BYTEORDER_H_