M5Utility 0.3.0 git rev:41a629c
Loading...
Searching...
No Matches
conversion.hpp File Reference

Numeric conversion. More...

#include <type_traits>
#include <limits>
#include <cstdint>
#include <cstddef>

Go to the source code of this file.

Namespaces

namespace  m5
 Top level namespace of M5.
 

Functions

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.
 

Detailed Description

Numeric conversion.

Function Documentation

◆ 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
ToDestination unsigned integer type
FromSource unsigned integer type
Parameters
vValue to convert
Returns
v, or the maximum of To when v exceeds it
// 0x1FFFF does not fit in uint16_t
uint16_t u16 = saturate_cast<uint16_t>(size_t{0x1FFFF});
// u16 is 0xFFFF (Not 0xFFFF & 0x1FFFF == 0xFFFF... it saturates, it does not wrap)
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
BitsNumber of bits assumed by value
uint32_t u24{0x00FFFFFF};
// 24 bit unsigned int to int32_t
uint32_t s32 = unsigned_to_signed<24>(u24);
// s32 is -1 (Not 16777215)

◆ 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
TUnsigned integer type of the value
Parameters
vValue to convert
bitsNumber of bits assumed by value (1 to the width of T; 0 yields 0)
// A table-driven field whose width is only known at run time
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