M5Utility 0.0.2 git rev:5c1a751
Loading...
Searching...
No Matches
conversion.hpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2024 M5Stack Technology CO LTD
3 *
4 * SPDX-License-Identifier: MIT
5 */
10#ifndef M5_UTILITY_CONVERSION_HPP
11#define M5_UTILITY_CONVERSION_HPP
12
13#include <type_traits>
14#include <cstdint>
15#include <cstddef>
16
17namespace m5 {
18namespace utility {
19
31template <size_t Bits, typename T>
32constexpr auto unsigned_to_signed(const T v) -> typename std::make_signed<T>::type
33{
34 static_assert(std::is_integral<T>::value && std::is_unsigned<T>::value, "T must be an unsigned integer");
35 static_assert(Bits <= sizeof(T) * 8, "Bits must be less than or equal to the number of bits in T");
36
37 using S = typename std::make_signed<T>::type;
38 return static_cast<S>((v & (1ULL << (Bits - 1))) ? (v & ((1ULL << Bits) - 1)) - (1ULL << Bits)
39 : (v & ((1ULL << Bits) - 1)));
40}
41
42} // namespace utility
43} // namespace m5
44#endif
constexpr auto unsigned_to_signed(const T v) -> typename std::make_signed< T >::type
Convert an unsigned integer of any maximum number of bits to a signed integer.
Definition conversion.hpp:32
Top level namespace of M5.
Definition bit_segment.hpp:17
For utilities.