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_
16 #include "build/build_config.h"
18 #if defined(COMPILER_MSVC)
24 // Returns a value with all bytes in |x| swapped, i.e. reverses the endianness.
25 inline uint16_t ByteSwap(uint16_t x) {
26 #if defined(COMPILER_MSVC)
27 return _byteswap_ushort(x);
29 return __builtin_bswap16(x);
33 inline uint32_t ByteSwap(uint32_t x) {
34 #if defined(COMPILER_MSVC)
35 return _byteswap_ulong(x);
37 return __builtin_bswap32(x);
41 inline uint64_t ByteSwap(uint64_t x) {
42 #if defined(COMPILER_MSVC)
43 return _byteswap_uint64(x);
45 return __builtin_bswap64(x);
49 inline uintptr_t ByteSwapUintPtrT(uintptr_t x) {
50 // We do it this way because some build configurations are ILP32 even when
51 // defined(ARCH_CPU_64_BITS). Unfortunately, we can't use sizeof in #ifs. But,
52 // because these conditionals are constexprs, the irrelevant branches will
53 // likely be optimized away, so this construction should not result in code
55 static_assert(sizeof(uintptr_t) == 4 || sizeof(uintptr_t) == 8,
56 "Unsupported uintptr_t size");
57 if (sizeof(uintptr_t) == 4)
58 return ByteSwap(static_cast<uint32_t>(x));
59 return ByteSwap(static_cast<uint64_t>(x));
62 // Converts the bytes in |x| from host order (endianness) to little endian, and
63 // returns the result.
64 inline uint16_t ByteSwapToLE16(uint16_t x) {
65 #if defined(ARCH_CPU_LITTLE_ENDIAN)
71 inline uint32_t ByteSwapToLE32(uint32_t x) {
72 #if defined(ARCH_CPU_LITTLE_ENDIAN)
78 inline uint64_t ByteSwapToLE64(uint64_t x) {
79 #if defined(ARCH_CPU_LITTLE_ENDIAN)
86 // Converts the bytes in |x| from network to host order (endianness), and
87 // returns the result.
88 inline uint16_t NetToHost16(uint16_t x) {
89 #if defined(ARCH_CPU_LITTLE_ENDIAN)
95 inline uint32_t NetToHost32(uint32_t x) {
96 #if defined(ARCH_CPU_LITTLE_ENDIAN)
102 inline uint64_t NetToHost64(uint64_t x) {
103 #if defined(ARCH_CPU_LITTLE_ENDIAN)
110 // Converts the bytes in |x| from host to network order (endianness), and
111 // returns the result.
112 inline uint16_t HostToNet16(uint16_t x) {
113 #if defined(ARCH_CPU_LITTLE_ENDIAN)
119 inline uint32_t HostToNet32(uint32_t x) {
120 #if defined(ARCH_CPU_LITTLE_ENDIAN)
126 inline uint64_t HostToNet64(uint64_t x) {
127 #if defined(ARCH_CPU_LITTLE_ENDIAN)
136 #endif // BASE_SYS_BYTEORDER_H_