将long.MaxValue转换为int和将float.MaxValue转换为int有什么区别? [英] What is the difference between casting long.MaxValue to int and casting float.MaxValue to int?

查看:85
本文介绍了将long.MaxValue转换为int和将float.MaxValue转换为int有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解某些数据类型与转换之间的区别。

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

我知道,如果要分配给整数的值大于该整数可以保留的值,它将返回整数的最小值(-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).

据我所知, long.MaxValue 远远大于整数的最大值,但是如果我强制转换 long.MaxValue int ,它返回-1。

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.

这两个强制转换有什么区别?我认为第一个也应该返回-2147483648而不是-1。

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

推荐答案

让我解释一下:

long longValue=long.MaxValue;
float floatValue = float.MaxValue;
int integerValue = (int) longValue;
int integerValue2 = (int)floatValue;

long的最大值为9,223,372,036,854,775,807或0x7FFFFFFFFFFFFFFF,因此将2的补码数减为0xFFFFFFFF后将返回0x00000001

The maximum value of long is 9,223,372,036,854,775,807 or 0x7FFFFFFFFFFFFFFF, thus 2's complement after reducing it into 0xFFFFFFFF will return 0x00000001 with minus sign bit, represented as -1 in decimal.

另一方面,float的最大值为3.40282347E + 38,因此将其强制转换为int四舍五入值设为3E + 38,并在减少后使用2的补码得到带有负号位的十六进制值0x80000000,十进制为-2147483648。

On the other side, the maximum value of float is 3.40282347E+38, thus casting it to int rounded the value to 3E+38 and using 2's complement after reducing it we get the hex value of 0x80000000 with minus sign bit, there is -2147483648 in decimal.

引用:

https://msdn.microsoft.com/zh-我们/library/system.int64.maxvalue(v=vs.110).aspx

https://msdn.microsoft.com/zh- us / library / system.single.maxvalue(v = vs.110).aspx

这篇关于将long.MaxValue转换为int和将float.MaxValue转换为int有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆