Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between casting long.MaxValue to int and casting float.MaxValue to int?

Tags:

c#

types

casting

I'm trying to understand difference between some data types and conversion.

public static void ExplicitTypeConversion2()
    {
        long longValue=long.MaxValue;
        float floatValue = float.MaxValue;
        int integerValue = (int) longValue;
        int integerValue2 = (int)floatValue;
        Console.WriteLine(integerValue);
        Console.WriteLine(integerValue2);            
    }

When I run that code block, it outputs:

-1
-2147483648

I know that if the value you want to assign to an integer is bigger than that integer can keep, it returns the minimum value of integer (-2147483648).

As far as I know, long.MaxValue is much bigger than the maximum value of an integer, but if I cast long.MaxValue to int, it returns -1.

What is the difference these two casting? I think the first one also suppose to return -2147483648 instead of -1.

like image 745
Tuncaf Avatar asked Jun 16 '16 08:06

Tuncaf


People also ask

What is long MaxValue in C#?

Represents the largest possible value of an Int64. This field is constant. public: long MaxValue = 9223372036854775807; C# Copy.

What is the value of INT MaxValue?

Remarks. The value of this constant is 2,147,483,647; that is, hexadecimal 0x7FFFFFFF.

What is a limitation of ints compared to floats?

int can hold only integer numbers, whereas float also supports floating point numbers (as the type names suggest). How is it possible then that the max value of int is 231, and the max value of float is 3.4*1038, while both of them are 32 bits?


1 Answers

if the value you want to assign to an integer, bigger than that integer can keep, returns minimum value of integer

That's not a rule. The relevant rules are

For integer types in an unchecked context (ie the default):

If the source type is larger than the destination type, then the source value is truncated by discarding its “extra” most significant bits. The result is then treated as a value of the destination type.

For float->int in an unchecked context:

The value is rounded towards zero to the nearest integral value. If this integral value is within the range of the destination type, then this value is the result of the conversion. Otherwise, the result of the conversion is an unspecified value of the destination type.

Chopping off 32 leading bits of off 0x7fffffffffffffff gives 0xffffffff aka -1.

You were never promised you would get int.MinValue for that out of range float->int cast, but you do anyway because it's easy to implement: x64's conversion instruction cvtss2si makes 0x80000000 for out of range results and similarly fistp (the old x87 conversion instruction used by the 32bit JIT) stores "the integer indefinite value" which is 0x80000000.

like image 78
harold Avatar answered Sep 18 '22 08:09

harold