aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/bswap.h
blob: b322b9d9b0baac3b9a0e6a650b5ae74bd9ec9863 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*************************************************
* Byte Swapping Operations Header File           *
* (C) 1999-2008 Jack Lloyd                       *
*************************************************/

#ifndef BOTAN_BYTE_SWAP_H__
#define BOTAN_BYTE_SWAP_H__

#include <botan/types.h>
#include <botan/rotate.h>

namespace Botan {

/*************************************************
* Byte Swapping Functions                        *
*************************************************/
inline u16bit reverse_bytes(u16bit input)
   {
   return rotate_left(input, 8);
   }

inline u32bit reverse_bytes(u32bit input)
   {
#if BOTAN_COMPILER_HAS_GCC_INLINE_ASM && \
    (defined(BOTAN_TARGET_ARCH_IS_IA32) || defined(BOTAN_TARGET_ARCH_IS_AMD64))

   asm("bswapl %0" : "=r" (input) : "0" (input));
   return input;
#else
   input = ((input & 0xFF00FF00) >> 8) | ((input & 0x00FF00FF) << 8);
   return rotate_left(input, 16);
#endif
   }

inline u64bit reverse_bytes(u64bit input)
   {
#if BOTAN_COMPILER_HAS_GCC_INLINE_ASM && defined(BOTAN_TARGET_ARCH_IS_AMD64)
   asm("bswapq %0" : "=r" (input) : "0" (input));
   return input;
#else
   u32bit hi = ((input >> 40) & 0x00FF00FF) | ((input >> 24) & 0xFF00FF00);
   u32bit lo = ((input & 0xFF00FF00) >> 8) | ((input & 0x00FF00FF) << 8);
   hi = (hi << 16) | (hi >> 16);
   lo = (lo << 16) | (lo >> 16);
   return (static_cast<u64bit>(lo) << 32) | hi;
#endif
   }

}

#endif