This week's giveaway is in the Spring forum. We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line! See this thread for details.

int i =10; byte b = i; --- >Gives an error: cant put int (32 bits) into byte (8bits) - AND thts understandable long L =10; float f = L; --->Doesnt throw error ? why?? How can u put a 64 bit long into a 32 bit float??... why doesnt the int-byte logic work here??

Originally posted by Mr. Multeon: long L =10; float f = L; --->[b]Doesnt throw error ? why??

This is still considered as promotion. Remember the primitive type heirarchy? So you are still going 'up the chain', so to speak. A floating point is stored in exponential form. So its accuracy will depend on how many bits are allocated for its mantissa and exponent(I don't know exactly how much for Java) So assigning long to float is still OK. It will just convert it to its exponential form. However, this does not guarantee that it can preserve the original value. Precision may still be lost.

Here is a program that finds the first long that cannot be represented exactly as a float.

1 0000 0000 0000 0000 0000 0001 A float has 23 bits for the fraction part. This number needs 24 bits.

Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391

posted

0

A 32-bit floating point number looks like this 1 bit for the sign 8 bits for the exponent (unsigned 0-255) 23 bits for the signficand (fraction) The way you convert a long to a float is 1. Write the long as a binary number 2. Write the number in normalized form 1.xxxxxxxxxxx 3. Since the most significant digit will always be 1, drop that digit. 4. Put the most significant 23 digits into the significand 5. Compute the exponent and add 127 (2^-1 -> 126, 2^0 -> 127, 2^1 -> 128) [ June 12, 2003: Message edited by: Marlene Miller ]