aboutsummaryrefslogtreecommitdiff
path: root/utils.h
blob: ba13f2752c2e525f037d89f3a6a61b2c0ac8fd46 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <limits>
#include <stdexcept>

/*
 * Credits to:
 * http://stackoverflow.com/questions/13150449/efficient-unsigned-to-signed-cast-avoiding-implementation-defined-behavior
 */
template<typename Uint, typename Int>
Int uintToInt(Uint x)
{
    if (x <= std::numeric_limits<Int>::max())
        return static_cast<Int>(x);

    if (x >= std::numeric_limits<Int>::min())
        return static_cast<Int>(x - std::numeric_limits<Int>::min())
             + std::numeric_limits<Int>::min();

    throw std::overflow_error("given value does not fit integer type");
}