[英]Long is of size 8 bytes then how can it be 'promoted' to float(4 bytes) in JAVA?
I read that in Java the long type can be promoted float and double ( http://www.javatpoint.com/method-overloading-in-java ). 我在Java中读到long类型可以提升float和double( http://www.javatpoint.com/method-overloading-in-java )。 I wanted to ask that long integer takes 8 bytes of memory in JAVA and float takes 4 bytes then how this promotion works? 我想问一下,长整数在JAVA中占用8个字节的内存,浮点数需要4个字节,然后这个促销如何工作? Isn't it possible that we could be facing some data loss if we promote this way? 如果我们以这种方式推广,我们是否有可能面临一些数据丢失?
Also it is noticeable that all other type promotions are from smaller size primitive datatype to similar or larger size datatypes. 另外值得注意的是,所有其他类型的促销都是从较小尺寸的原始数据类型到类似或更大尺寸的数据类型。
long
uses more bytes, but it has a smaller range: while long
cannot go above 2 63 , float
can go to about 2 127 . long
使用更多的字节,但它的范围更小:虽然long
不能超过2 63 ,但float
可以达到约2 127 。 Obviously, the expansion of range comes at the price of lower precision, but since the range of float
is larger, the conversion from long
to float
is a promotion. 显然,范围的扩大是以较低的精度为代价的,但由于float
范围较大,因此从long
到float
的转换是一种促销。
float
is represented in a different way than integral types. float
以与整数类型不同的方式表示。 For further infos on the floating-type, read this: https://en.wikipedia.org/wiki/Single-precision_floating-point_format . 有关浮动类型的更多信息,请阅读: https : //en.wikipedia.org/wiki/Single-precision_floating-point_format 。 The content cooked down would look like this: the floating-point format consists of a sign-bit, 8 bits for the exponent and 23 bits for the fractional part of the value. 熟化的内容如下所示:浮点格式由符号位组成,指数为8位,值的小数部分为23位。 The value is calculated like this: (-1)^signbit * 1.fractionalpart * 2 ^ (exponent - 127). 该值的计算如下:( - 1)^ signbit * 1.fractionalpart * 2 ^(指数 - 127)。 Thus this algorithm allows representation of larger values than a 64bit integral type. 因此,该算法允许表示比64位整数类型更大的值。
This quick test should show why: 这个快速测试应该说明原因:
public class Main {
public static void main(String[] args) {
System.out.println("Float: " + Float.MAX_VALUE);
System.out.println("Long: " + Long.MAX_VALUE);
}
}
Ouput: 输出继电器:
Float: 3.4028235E38
Long: 9223372036854775807
Note the scientific notation in the Float line. 请注意Float系列中的科学记数法。 The Float takes up less space, but due to its representation, it can hold up to a larger number than a Long. Float占用的空间较少,但由于它的表现,它可以容纳比Long更大的数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.