0

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?

jayjay
  • 1,017
  • 1
  • 11
  • 23
  • 1
    That's just not possible. No integer type covers the full float/double range. – undur_gongor Jul 04 '14 at 09:11
  • @undur_gongor at least no integer type is **guaranteed** to cover it. In C, integer types only have *minimal* widths, not maximal ones. – The Paramagnetic Croissant Jul 04 '14 at 09:12
  • 2
    Check the value of the float and see if it fits. If it doesn't, blow up the universe to ensure "not under any circumstances". – Kerrek SB Jul 04 '14 at 09:14
  • If you want an integer type that will cover a larger range than the built-in types, you might be interested in the answers to this question: http://stackoverflow.com/questions/565150/bigint-in-c – Tom Fenech Jul 04 '14 at 09:24
  • @user3477950: You are right. There could be 129 bit integers that would cover the full IEEE754 single range. – undur_gongor Jul 04 '14 at 09:25

2 Answers2

2

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.

Jonny
  • 2,509
  • 23
  • 42
  • 3
    "but the range for `long long` is such and such" -- **at least.** Nothing prevents an implementation from supplying a, say, 1024-bit wide `long long`. – The Paramagnetic Croissant Jul 04 '14 at 09:26
  • 2
    This answer would make sense if the question was about Visual C++, but there is no sign in the question that this is what the OP uses. – Pascal Cuoq Jul 04 '14 at 09:29
0

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.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85