[ create a new paste ] login | about

Link: http://codepad.org/rF5phWTh    [ raw code | output | fork ]

pyrtsa_ - C++, pasted on Oct 12:
#include <limits>

template <typename T> T clamp(T x, T lower, T upper) {
    if (x < lower) return lower;
    if (x > upper) return upper;
    return x;
}

short normalized_float_to_short(float x) {
    return short(clamp(x, -1.0f, 1.0f) * std::numeric_limits<short>::max());
}

// --- test ---

#include <iostream>

int main() {
    std::cout << normalized_float_to_short(-2.0f) << std::endl;
    std::cout << normalized_float_to_short(-1.0f) << std::endl;
    std::cout << normalized_float_to_short(-0.5f) << std::endl;
    std::cout << normalized_float_to_short(-0.1f) << std::endl;
    std::cout << normalized_float_to_short( 0.0f) << std::endl;
    std::cout << normalized_float_to_short( 0.1f) << std::endl;
    std::cout << normalized_float_to_short( 0.5f) << std::endl;
    std::cout << normalized_float_to_short( 1.0f) << std::endl;
    std::cout << normalized_float_to_short(10.0f) << std::endl;
}


Output:
1
2
3
4
5
6
7
8
9
-32767
-32767
-16383
-3276
0
3276
16383
32767
32767


Create a new paste based on this one


Comments: