Botan
3.14.1
Crypto and TLS for C&
src
lib
utils
bswap.h
Go to the documentation of this file.
1
/*
2
* Byte Swapping Operations
3
* (C) 1999-2011,2018 Jack Lloyd
4
* (C) 2007 Yves Jerschow
5
* (C) 2024 René Meusel - Rohde & Schwarz Cybersecurity
6
*
7
* TODO: C++23: replace this entire implementation with std::byteswap
8
*
9
* Botan is released under the Simplified BSD License (see license.txt)
10
*/
11
12
#ifndef BOTAN_BYTE_SWAP_H_
13
#define BOTAN_BYTE_SWAP_H_
14
15
#include <botan/compiler.h>
16
#include <concepts>
17
18
namespace
Botan
{
19
20
/**
21
* Swap the byte order of an unsigned integer
22
*/
23
template
<std::
unsigned
_
int
egral T>
24
requires
(
sizeof
(T) == 1 ||
sizeof
(T) == 2 ||
sizeof
(T) == 4 ||
sizeof
(T) == 8)
25
inline
constexpr
T
reverse_bytes
(T x) {
26
if
constexpr
(
sizeof
(T) == 1) {
27
return
x;
28
}
else
if
constexpr
(
sizeof
(T) == 2) {
29
#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap16)
30
return
static_cast<
T
>
(__builtin_bswap16(x));
31
#else
32
return
static_cast<
T
>
((x << 8) | (x >> 8));
33
#endif
34
}
else
if
constexpr
(
sizeof
(T) == 4) {
35
#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap32)
36
return
static_cast<
T
>
(__builtin_bswap32(x));
37
#else
38
// MSVC at least recognizes this as a bswap
39
return
static_cast<
T
>
(((x & 0x000000FF) << 24) | ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8) |
40
((x & 0xFF000000) >> 24));
41
#endif
42
}
else
if
constexpr
(
sizeof
(T) == 8) {
43
#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap64)
44
return
static_cast<
T
>
(__builtin_bswap64(x));
45
#else
46
uint32_t hi =
static_cast<
uint32_t
>
(x >> 32);
47
uint32_t lo =
static_cast<
uint32_t
>
(x);
48
49
hi =
reverse_bytes
(hi);
50
lo =
reverse_bytes
(lo);
51
52
return
(
static_cast<
T
>
(lo) << 32) | hi;
53
#endif
54
}
55
}
56
57
}
// namespace Botan
58
59
#endif
Botan
Definition
alg_id.cpp:14
Botan::reverse_bytes
constexpr T reverse_bytes(T x)
Definition
bswap.h:25
Generated by
1.16.1