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

后端 未结 4 664
执笔经年
执笔经年 2021-02-13 16:28

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 17:07

    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.

提交回复
热议问题