# storing a long in a float with same precision on Solaris 64bit OS

Discussion in 'C Programming' started by Nishant Deshpande, Jul 18, 2003.

1. ### Nishant DeshpandeGuest

On Solaris 64-bit:

sizeof(long) = 8
sizeof(double) = 8 !!!

So i figure i can't store a long with the same precision in a double.
But, when i create a long and assign its largest value to it, then
assign this to a double, then subtract the double from the long, I get
0.

I see from the include files the exponent is 11 bits. So the Mantissa
must be 53 (or less) bits. So how can the double store my long to the
same precision??

I've posted the code and output below.

Any help appreciated.

Nishant

------------------------------
#include <stdlib.h>
#include <iostream.h>
#include <stdio.h>

int main()
{
cout << sizeof(long) << endl;
cout << sizeof(double) << endl;
cout << sizeof(float) << endl;

long l = 0x7FFFFFFFFFFFFFFF;
//long l = 9223372036854775807LL;
cout << "l = " << l << endl;

// want to confirm l is indeed the largest long
long nl = l + 1;
cout << "nl = " << nl << endl;

double d = l;
cout << "d = " << d << endl;

double r = d / l;
cout << "r = " << r << endl;

double rr = l - d;
cout << "rr = " << rr << endl;

}

--------
output:

8
8
4
l = 9223372036854775807
nl = -9223372036854775808
d = 9.22337e+18
r = 1
rr = 0

-------------------

Nishant Deshpande, Jul 18, 2003

2. ### Erik de Castro LopoGuest

Nishant Deshpande wrote:
>
> On Solaris 64-bit:
>
> sizeof(long) = 8
> sizeof(double) = 8 !!!
>
> So i figure i can't store a long with the same precision in a double.

You can store SOME longs in a double without loss os precision,
but definitely not all longs.

In a double, I believe that 13 bits are used for the exponent and
one for the sign. These take away from the mantissa, so the largest
64 bit long that can be represented as a double is 51 bits long
or

-(2^51) to (2^51) - 1

If you look at this a little more closely, it is actually less
than 1 in 2^13 of all valif 64 bit longs.

Erik
--
+-----------------------------------------------------------+
Erik de Castro Lopo (Yes it's valid)
+-----------------------------------------------------------+
"The Internet interprets censorship as damage, and routes around it."
-- John Gilmore

Erik de Castro Lopo, Jul 19, 2003