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.
Represents the largest possible value of an Int64. This field is constant. public: long MaxValue = 9223372036854775807; C# Copy.
Remarks. The value of this constant is 2,147,483,647; that is, hexadecimal 0x7FFFFFFF.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With