Numeric conversion.
More...
#include <type_traits>
#include <limits>
#include <cstdint>
#include <cstddef>
Go to the source code of this file.
|
| namespace | m5 |
| | Top level namespace of M5.
|
| |
|
| template<size_t Bits, typename T > |
| constexpr auto | m5::utility::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.
|
| |
| template<typename T > |
| constexpr auto | m5::utility::unsigned_to_signed (const T v, const size_t bits) -> typename std::make_signed< T >::type |
| | Convert an unsigned integer to a signed integer, with the number of bits given at run time.
|
| |
| template<typename To , typename From > |
| constexpr To | m5::utility::saturate_cast (const From v) |
| | Narrows an unsigned integer, saturating at the maximum of the destination.
|
| |
◆ saturate_cast()
template<typename To , typename From >
| To m5::utility::saturate_cast |
( |
const From | v | ) |
|
|
constexpr |
Narrows an unsigned integer, saturating at the maximum of the destination.
- Template Parameters
-
| To | Destination unsigned integer type |
| From | Source unsigned integer type |
- Parameters
-
- Returns
- v, or the maximum of To when v exceeds it
uint16_t u16 = saturate_cast<uint16_t>(size_t{0x1FFFF});
- Note
- Only unsigned to unsigned for now. The comparison goes through uintmax_t, so a From narrower than To is handled as well
◆ unsigned_to_signed() [1/2]
template<size_t Bits, typename T >
| auto m5::utility::unsigned_to_signed |
( |
const T | v | ) |
-> typename std::make_signed<T>::type
|
|
constexpr |
Convert an unsigned integer of any maximum number of bits to a signed integer.
- Template Parameters
-
| Bits | Number of bits assumed by value uint32_t u24{0x00FFFFFF};
uint32_t s32 = unsigned_to_signed<24>(u24);
|
◆ unsigned_to_signed() [2/2]
template<typename T >
| auto m5::utility::unsigned_to_signed |
( |
const T | v, |
|
|
const size_t | bits ) -> typename std::make_signed<T>::type
|
|
constexpr |
Convert an unsigned integer to a signed integer, with the number of bits given at run time.
- Template Parameters
-
| T | Unsigned integer type of the value |
- Parameters
-
| v | Value to convert |
| bits | Number of bits assumed by value (1 to the width of T; 0 yields 0)
int32_t s = unsigned_to_signed(raw, signal.bit_length);
|
- Note
- Use the unsigned_to_signed<Bits>() overload whenever the width is a constant: it can check the width against T at compile time, which this one cannot