归一化到/从浮点数转换整数 [英] Normalized Integer to/from Float Conversion
问题描述
这是一个使用 std :: numeric_limits
的模板化解决方案:
#include< cstdint>
#include< limits>
模板< typename T>
constexpr double normalize(T value){
返回值< 0
? -static_cast< double>(value)/ std :: numeric_limits< T> :: min()
:static_cast< double>(value)/ std :: numeric_limits< T> :: max ;
}
int main(){
//测试用例在编译时计算。
static_assert(normalize(int16_t(32767))== 1,);
static_assert(normalize(int16_t(0))== 0,);
static_assert(normalize(int16_t(-32768))== -1,);
static_assert(normalize(int16_t(-16384))== -0.5,);
static_assert(normalize(uint16_t(65535))== 1,);
static_assert(normalize(uint16_t(0))== 0,);
$ b 这个处理有符号整数和无符号整数,0标准化为0。 / p>
I need to convert normalized integer values to and from real floating-point values. For instance, for int16_t, a value of 1.0 is represented by 32767 and -1.0 is represented by -32768. Although it's a bit tedious to do this for each integer type, both signed and unsigned, it's still easy enough to write by hand.
However, I want to use standard methods whenever possible rather than going off and reinventing the wheel, so what I'm looking for is something like a standard C or C++ header, a Boost library, or some other small, portable, easily-incorporated source that already performs these conversions.
解决方案 Here's a templated solution using std::numeric_limits
:
#include <cstdint>
#include <limits>
template <typename T>
constexpr double normalize (T value) {
return value < 0
? -static_cast<double>(value) / std::numeric_limits<T>::min()
: static_cast<double>(value) / std::numeric_limits<T>::max()
;
}
int main () {
// Test cases evaluated at compile time.
static_assert(normalize(int16_t(32767)) == 1, "");
static_assert(normalize(int16_t(0)) == 0, "");
static_assert(normalize(int16_t(-32768)) == -1, "");
static_assert(normalize(int16_t(-16384)) == -0.5, "");
static_assert(normalize(uint16_t(65535)) == 1, "");
static_assert(normalize(uint16_t(0)) == 0, "");
}
This handles both signed and unsigned integers, and 0 does normalize to 0.
View Successful Compilation Result
这篇关于归一化到/从浮点数转换整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!