top | item 22067773

(no title)

ambrop7 | 6 years ago

Here's a reliable/portable solution:

    bool double_to_uint64 (double x, uint64_t *out)
    {
        double y = trunc(x);
        if (y >= 0.0 && y < ldexp(1.0, 64)) {
            *out = y;
            return true;
        } else {
            return false;
        }
    }
If you need different rounding behavior, just change trunc() to round(), floor() or ceil(). Note that it is important that the result is produced by converting the rounded double (y) to an integer type, not the original value (x).

Explanation:

- we first round the value to an integer (but still a floating point value),

- we then check that this integer is in the valid range of the target integer type by comparing it with exact integer values (0 and 2^N),

- if the check passes, then converting this integer to the target integer type is safe, and if the check fails, then conversion is not possible.

Of course if you literally need to convert to "long" you have a problem because the width of "long" is not known, but that is a rather different concern. I argue types with unknown width like "long" should almost never be used anyway.

(based on my answer here: https://stackoverflow.com/questions/8905246/how-to-check-if-...)

discuss

order

No comments yet.