How do I convert an arbitrary double to an integer while avoiding undefined behavior?

后端 未结 4 1621
你的背包
你的背包 2021-02-13 16:27

Let\'s say I\'ve got a function that accepts a 64-bit integer, and I want to call it with a double with arbitrary numeric value (i.e. it may be very large in magnit

4条回答
  •  有刺的猬
    2021-02-13 16:53

    How about:

    constexpr uint64_t weird_high_limit = (double)kint64max == (double)(kint64max-1);
    int64_t clamped = (d >= weird_high_limit + kint64max)? kint64max: (d <= kint64min)? kint64min: int64_t(d);
    

    I think this takes care of all the edge cases. If d < (double)kint64max, then (exact)d <= (exact)kint64max. Proof proceeds by contradiction of the fact that (double)kint64max is the next higher or lower representable value.

提交回复
热议问题