jayjay
jayjay

Reputation: 1047

Casting a double or float to an integer type, which type?

If I wanted to cast a float or double to an integer type, and I didnt want it to overflow under any circumstances, how should I go about choosing an integer type?

Upvotes: 0

Views: 102

Answers (2)

David C. Rankin
David C. Rankin

Reputation: 84561

There is a simple way to cast int to float and back. It is possible because of most modern computers share 32bit storage. What this allows is using a union. for example:

    union
    {
        float x;
        int i;
    } u;

Here you are free to assign a float u.x=391 and then make use of the integer representation int myint = u.i There is nothing to prevent the use with other storage classes. However, you must check the most significant bit and insure 1 <= msb < 32 or you are guaranteed to fail. In the instance where a double has a msb < 32 it receive like treatment.

This is not recommended and is as best implementation defined behavior. The numeric storage of floats in ieee754 format define the 32bit storage. It in itself in an entire other discussion. You can test this method, look at the ieee754 storage format and understand the limitations they pose.

Upvotes: 0

Jonny
Jonny

Reputation: 2519

The range for floats is almost always larger than the long long or int64 (but it can depend on the implementation).

For example, in .Net the range of float is 3.4E +/- 38 , but the range for long long and int64 is –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. You just can't be sure that you will not overflow. Other implementations of C and C++ have similar ranges.

Source: http://msdn.microsoft.com/en-us/library/s3f49ktz.aspx.

Upvotes: 2

Related Questions