Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

conversion from long to float

 
Suneela Joshi
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Long is 64 bytes and both int and float are 32 bytes. Why can a long
be assigned to a float without an explicit cast but an int can not?
If a long is declared as follows:
long l = 123456L;
This doesn't implicitly convert
int i = l; // Gives a compile error as expected
but doing this safely compiles and run.
float f = l;
Can someone please explain?
Thanks
 
Vinod Venkatasubramanian
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The way floats are stored internally (in the form of exponents) gives it a larger range and hence makes it safe to cast a long to a float.
Long to int of course might lead to possible loss of info.
 
Inquisitive M.
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good question. A floating point number uses essentially the binary
version of scientific notation... so it can express the very large
possible values of long variables, but with a loss of *precision*. That
is, I might convert (this example by analogy is actually using decimal
precisions) 23472166003027 into (2.34722 * 10^13) as a floating point
number.
Whether this should be considered a widening conversion (and thus not
need a cast) is a debatable point, but the Java design team decided that
it should. On the pro side, you do get a reasonable value, even if
precision is lost (compare with, for example, converting long to int,
where a value out of range creates a practically random numeric result).
On the con side, it *is* a loss of precision, so perhaps the user should
be warned about it.
I'm always in favor of compiler checks, so I disagree with Java's choice
on this one.
If this would help, this is the data from IEEE 754 Floating Point which Java complies :
A float is 4 bytes, 32 bits,
With 6 to 7 significant digits of accuracy.
covers a range from �1.40129846432481707e-45 to �3.40282346638528860e+38,
is formed of 3 fields:
1-bit sign
8-bit base 2 exponent biased+127
23-bit fraction, lead 1 implied
e.g. 3. = 0x404000
-3. = 0xC04000
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic