C/C++ API Reference
Loading...
Searching...
No Matches
bit.h
1// Copyright 2022 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15// Low-level bit operations including std::endian from C++20.
16#pragma once
17
18#include <climits>
19
20#include "lib/stdcompat/bit.h"
21
22namespace pw {
23
24using ::cpp20::endian;
25
27
28namespace bytes {
29
31#define SIZE_OF_IN_BIT(...) (sizeof(__VA_ARGS__) * CHAR_BIT)
32
35template <std::size_t kBitWidth, typename T>
36constexpr T SignExtend(T nbit_value) {
37 static_assert(std::is_integral_v<T>);
38 static_assert(kBitWidth < SIZE_OF_IN_BIT(T));
39
40 using SignedT = std::make_signed_t<T>;
41
42 constexpr std::size_t extension_bits = SIZE_OF_IN_BIT(SignedT) - kBitWidth;
43
44 SignedT nbit_temp = static_cast<SignedT>(nbit_value);
45 return ((nbit_temp << extension_bits) >> extension_bits);
46}
47
64template <typename OutType, std::size_t kMsb, std::size_t kLsb, typename InType>
65constexpr OutType ExtractBits(InType value) {
66 static_assert(kMsb >= kLsb);
67 static_assert(kMsb < SIZE_OF_IN_BIT(InType));
68
69 constexpr std::size_t kBitWidth = kMsb - kLsb + 1;
70 static_assert(kBitWidth <= SIZE_OF_IN_BIT(OutType));
71
72 if constexpr (kBitWidth == SIZE_OF_IN_BIT(InType)) {
73 return OutType(value);
74 } else {
75 constexpr OutType mask = OutType((OutType(1) << kBitWidth) - 1);
76 return OutType((value >> kLsb) & mask);
77 }
78}
79
80} // namespace bytes
81
83
84} // namespace pw
The Pigweed namespace.
Definition: alignment.h:27