Botan  2.4.0
Crypto and TLS for C++11
bswap.h
Go to the documentation of this file.
1 /*
2 * Byte Swapping Operations
3 * (C) 1999-2011 Jack Lloyd
4 * (C) 2007 Yves Jerschow
5 *
6 * Botan is released under the Simplified BSD License (see license.txt)
7 */
8 
9 #ifndef BOTAN_BYTE_SWAP_H_
10 #define BOTAN_BYTE_SWAP_H_
11 
12 #include <botan/types.h>
13 #include <botan/rotate.h>
14 
15 #if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
16  #include <stdlib.h>
17 #endif
18 
19 namespace Botan {
20 
21 /**
22 * Swap a 16 bit integer
23 */
24 inline uint16_t reverse_bytes(uint16_t val)
25  {
26  return rotl<8>(val);
27  }
28 
29 /**
30 * Swap a 32 bit integer
31 */
32 inline uint32_t reverse_bytes(uint32_t val)
33  {
34 #if defined(BOTAN_BUILD_COMPILER_IS_GCC) || defined(BOTAN_BUILD_COMPILER_IS_CLANG)
35  return __builtin_bswap32(val);
36 
37 #elif defined(BOTAN_BUILD_COMPILER_IS_MSVC)
38  return _byteswap_ulong(val);
39 
40 #elif defined(BOTAN_USE_GCC_INLINE_ASM) && defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
41 
42  // GCC-style inline assembly for x86 or x86-64
43  asm("bswapl %0" : "=r" (val) : "0" (val));
44  return val;
45 
46 #else
47 
48  // Generic implementation
49  return (rotr<8>(val) & 0xFF00FF00) | (rotl<8>(val) & 0x00FF00FF);
50 
51 #endif
52  }
53 
54 /**
55 * Swap a 64 bit integer
56 */
57 inline uint64_t reverse_bytes(uint64_t val)
58  {
59 #if defined(BOTAN_BUILD_COMPILER_IS_GCC) || defined(BOTAN_BUILD_COMPILER_IS_CLANG)
60  return __builtin_bswap64(val);
61 
62 #elif defined(BOTAN_BUILD_COMPILER_IS_MSVC)
63  return _byteswap_uint64(val);
64 
65 #elif defined(BOTAN_USE_GCC_INLINE_ASM) && defined(BOTAN_TARGET_ARCH_IS_X86_64)
66  // GCC-style inline assembly for x86-64
67  asm("bswapq %0" : "=r" (val) : "0" (val));
68  return val;
69 
70 #else
71  /* Generic implementation. Defined in terms of 32-bit bswap so any
72  * optimizations in that version can help.
73  */
74 
75  uint32_t hi = static_cast<uint32_t>(val >> 32);
76  uint32_t lo = static_cast<uint32_t>(val);
77 
78  hi = reverse_bytes(hi);
79  lo = reverse_bytes(lo);
80 
81  return (static_cast<uint64_t>(lo) << 32) | hi;
82 #endif
83  }
84 
85 /**
86 * Swap 4 Ts in an array
87 */
88 template<typename T>
89 inline void bswap_4(T x[4])
90  {
91  x[0] = reverse_bytes(x[0]);
92  x[1] = reverse_bytes(x[1]);
93  x[2] = reverse_bytes(x[2]);
94  x[3] = reverse_bytes(x[3]);
95  }
96 
97 }
98 
99 #endif
Definition: alg_id.cpp:13
void bswap_4(T x[4])
Definition: bswap.h:89
uint16_t reverse_bytes(uint16_t val)
Definition: bswap.h:24
fe T
Definition: ge.cpp:37