RESTinio
bitops.hpp
Go to the documentation of this file.
1/*
2 * restinio
3 */
4
9#pragma once
10
11#include <cstdint>
12
13namespace restinio {
14
15namespace utils{
16
17namespace impl {
18
19namespace bitops {
20
21namespace details {
22
23template< typename T >
24constexpr T mask( unsigned bits_to_extract )
25{
26 return bits_to_extract <= 1u ? T{1} :
27 static_cast<T>((mask<T>(bits_to_extract-1) << 1) | T{1});
28}
29
30template< typename T >
32
33template<>
34struct bits_count<std::uint8_t> { static constexpr unsigned count = 8u; };
35
36template<>
37struct bits_count<std::int8_t> { static constexpr unsigned count = 8u; };
38
39template<>
40struct bits_count<char> { static constexpr unsigned count = 8u; };
41
42template<>
43struct bits_count<std::uint16_t> { static constexpr unsigned count = 16u; };
44
45template<>
46struct bits_count<std::int16_t> { static constexpr unsigned count = 16u; };
47
48template<>
49struct bits_count<std::uint32_t> { static constexpr unsigned count = 32u; };
50
51template<>
52struct bits_count<std::int32_t> { static constexpr unsigned count = 32u; };
53
54template<>
55struct bits_count<std::uint64_t> { static constexpr unsigned count = 64u; };
56
57template<>
58struct bits_count<std::int64_t> { static constexpr unsigned count = 64u; };
59
60} /* namespace details */
61
80template<
81 typename T,
82 unsigned Shift,
83 unsigned Bits_To_Extract = details::bits_count<T>::count,
84 typename F = unsigned int >
85T
86n_bits_from( F value )
87{
88 return static_cast<T>(value >> Shift) & details::mask<T>(Bits_To_Extract);
89}
90
91} /* namespace bitops */
92
93} /* namespace impl */
94
95} /* namespace utils */
96
97} /* namespace restinio */
constexpr T mask(unsigned bits_to_extract)
Definition: bitops.hpp:24
T n_bits_from(F value)
Extract N bits from a bigger integer value.
Definition: bitops.hpp:86
STL namespace.