framework
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
byte_swap.hpp
Go to the documentation of this file.
1 // Copyright (C) 2012 iwg molw5
2 // For conditions of distribution and use, see copyright notice in COPYING
3 
13 #pragma once
14 
16 
17 namespace framework
18 {
22  template <typename T>
24  T bswap16 (T&& in)
25  {
26  static_assert(sizeof(T) == 2, "16-bit type expected");
27  uint16_t const x = static_cast <uint16_t> (in);
28  return static_cast <T> ((x >> 8) | (x << 8));
29  }
30 
34  template <typename T>
36  T bswap32 (T&& in)
37  {
38  static_assert(sizeof(T) == 4, "32-bit type expected");
39  uint32_t x = static_cast <uint32_t> (in);
40  x = ((x & 0xFF00FF00) >> 8) | ((x & 0x00FF00FF) << 8);
41  return static_cast <T> ((x >> 16) | (x << 16));
42  }
43 
47  template <typename T>
49  T bswap64 (T&& in)
50  {
51  static_assert(sizeof(T) == 8, "64-bit type expected");
52  uint64_t x = static_cast <uint64_t> (in);
53  x = ((x & 0xFF00FF00FF00FF00) >> 8) | ((x & 0x00FF00FF00FF00FF) << 8);
54  x = ((x & 0xFFFF0000FFFF0000) >> 16) | ((x & 0x0000FFFF0000FFFF) << 16);
55  return static_cast <T> ((x >> 32) | (x << 32));
56  }
57 }
58 
59 #if defined(__clang__)
60  // TODO - Check these definitions when 3.3 is released
61  #if MAX_CLANG_VERSION(3, 2, 0)
62  #define FRAMEWORK_BYTESWAP8(x) x
63  #define FRAMEWORK_BYTESWAP16(x) ::framework::bswap16(x)
64  #define FRAMEWORK_BYTESWAP32(x) __builtin_bswap32(x)
65  #define FRAMEWORK_BYTESWAP64(x) __builtin_bswap64(x)
66  #else
67  #define FRAMEWORK_BYTESWAP8(x) x
68  #define FRAMEWORK_BYTESWAP16(x) __builtin_bswap16(x)
69  #define FRAMEWORK_BYTESWAP32(x) __builtin_bswap32(x)
70  #define FRAMEWORK_BYTESWAP64(x) __builtin_bswap64(x)
71  #endif
72 #elif defined(__GNUC__)
73  #define FRAMEWORK_BYTESWAP8(x) x
74  #define FRAMEWORK_BYTESWAP16(x) ::framework::bswap16(x)
75  #define FRAMEWORK_BYTESWAP32(x) __builtin_bswap32(x)
76  #define FRAMEWORK_BYTESWAP64(x) __builtin_bswap64(x)
77 #else
78  #define FRAMEWORK_BYTESWAP8(x) x
79  #define FRAMEWORK_BYTESWAP16(x) ::framework::bswap16(x)
80  #define FRAMEWORK_BYTESWAP32(x) ::framework::bswap32(x)
81  #define FRAMEWORK_BYTESWAP64(x) ::framework::bswap64(x)
82 #endif