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
27namespace bytes {
28
30#define SIZE_OF_IN_BIT(...) (sizeof(__VA_ARGS__) * CHAR_BIT)
31
34template <std::size_t kBitWidth, typename T>
35constexpr T SignExtend(T nbit_value) {
36 static_assert(std::is_integral_v<T>);
37 static_assert(kBitWidth < SIZE_OF_IN_BIT(T));
38
39 using SignedT = std::make_signed_t<T>;
40
41 constexpr std::size_t extension_bits = SIZE_OF_IN_BIT(SignedT) - kBitWidth;
42
43 SignedT nbit_temp = static_cast<SignedT>(nbit_value);
44 return ((nbit_temp << extension_bits) >> extension_bits);
45}
46
63template <typename OutType, std::size_t kMsb, std::size_t kLsb, typename InType>
64constexpr OutType ExtractBits(InType value) {
65 static_assert(kMsb >= kLsb);
66 static_assert(kMsb < SIZE_OF_IN_BIT(InType));
67
68 constexpr std::size_t kBitWidth = kMsb - kLsb + 1;
69 static_assert(kBitWidth <= SIZE_OF_IN_BIT(OutType));
70
71 if constexpr (kBitWidth == SIZE_OF_IN_BIT(InType)) {
72 return OutType(value);
73 } else {
74 constexpr OutType mask = OutType((OutType(1) << kBitWidth) - 1);
75 return OutType((value >> kLsb) & mask);
76 }
77}
78
79} // namespace bytes
80} // namespace pw
constexpr OutType ExtractBits(InType value)
Definition: bit.h:64
constexpr T SignExtend(T nbit_value)
Definition: bit.h:35
The Pigweed namespace.
Definition: alignment.h:27