Botan 3.4.0
Crypto and TLS for C&
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*
6* TODO: C++23: replace this entire implementation with std::byteswap
7*
8* Botan is released under the Simplified BSD License (see license.txt)
9*/
10
11#ifndef BOTAN_BYTE_SWAP_H_
12#define BOTAN_BYTE_SWAP_H_
13
14#include <botan/types.h>
15
16namespace Botan {
17
18/**
19* Swap a 16 bit integer
20*/
21inline constexpr uint16_t reverse_bytes(uint16_t x) {
22#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap16)
23 return __builtin_bswap16(x);
24#else
25 return static_cast<uint16_t>((x << 8) | (x >> 8));
26#endif
27}
28
29/**
30* Swap a 32 bit integer
31*
32* We cannot use MSVC's _byteswap_ulong because it does not consider
33* the builtin to be constexpr.
34*/
35inline constexpr uint32_t reverse_bytes(uint32_t x) {
36#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap32)
37 return __builtin_bswap32(x);
38#else
39 // MSVC at least recognizes this as a bswap
40 return ((x & 0x000000FF) << 24) | ((x & 0x0000FF00) << 8) | ((x & 0x00FF0000) >> 8) | ((x & 0xFF000000) >> 24);
41#endif
42}
43
44/**
45* Swap a 64 bit integer
46*
47* We cannot use MSVC's _byteswap_uint64 because it does not consider
48* the builtin to be constexpr.
49*/
50inline constexpr uint64_t reverse_bytes(uint64_t x) {
51#if BOTAN_COMPILER_HAS_BUILTIN(__builtin_bswap64)
52 return __builtin_bswap64(x);
53#else
54 uint32_t hi = static_cast<uint32_t>(x >> 32);
55 uint32_t lo = static_cast<uint32_t>(x);
56
57 hi = reverse_bytes(hi);
58 lo = reverse_bytes(lo);
59
60 return (static_cast<uint64_t>(lo) << 32) | hi;
61#endif
62}
63
64} // namespace Botan
65
66#endif
constexpr uint16_t reverse_bytes(uint16_t x)
Definition bswap.h:21