Search code examples
rint64

How does bit64 store long long int in a double


When storing a whole number as a double, loss of precision stars occurring after 2^53:

> print(2^53, digits=20)
[1] 9007199254740992
> print(2^53+1, digits=20)
[1] 9007199254740992

The bit64 package in R can store integers up to 2^63:

> library(bit64)
> print(as.integer64(2)^53, digits=20)
[1] 9007199254740992
> print(as.integer64(2)^53+1, digits=20)
[1] 9007199254740993

However it looks like integer64 objects are just doubles dressed up with a special class:

> typeof(as.integer64(2)^53)
[1] "double"

How is it possible that a 32 bit double can store a 64 bit integer?


Solution

  • I know this is an old question, but it came up in a search I did and I was able to find the answer.

    As mdsumner commented, a double is 64-bit by definition. Doubles are stored in R's REALSXP type. The bit64 package converts the input from its various integer64 methods to uint64_t (which is supported by C99) and stores the 64-bits in R's REALSXP.