Trying to convert large integers to binary using as.binary

124 Views Asked by At

I have large integers that I need to convert to binary, but I keep getting this warning message:

Warning messages:

  1. In h(num) : probable complete loss of accuracy in modulus 2:
  2. In diff(x%%2^(num_digits:0)) : probable complete loss of accuracy in modulus

I have figured out that it's because converting a number to binary essentially is just dividing by two and determining if there is a remainder a whole bunch of times and R has a maximum number of digits that it is able to work with without losing the information at the end. Any suggestions on how to remedy this?

Example code:

library(binaryLogic)

as.binary(13256712356712312361)

[1] 1 0 1 1 0 1 1 1 1 1 1 1 1 0 0 1 0 1 0 0 1 1 0 1 1 0 1 0 0 1 1 0 1 0 1 1 1 1 1 1 0 1 0 1 1 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0

Warning messages:

  1. In h(num) : probable complete loss of accuracy in modulus
  2. In diff(x%%2^(num_digits:0)) : probable complete loss of accuracy in modulus
1

There are 1 best solutions below

0
On

I couldn't get it to work with an integer as big as the one I listed in my example, but this worked for integers of appropriate size for what I'm doing. (Max binary output for Rmpfr is 53 digits I believe, and the integer I listed requires 64 digits). Still, 53 digits is more than I was able to do with as.binary(). Example below is pretty close to the limit.

library(Rmpfr)

x <- unlist(strsplit(formatBin(1325671235671234),split = 'b', fixed = T))[2]
Dec <- as.integer(unlist(strsplit(x, split = '+', fixed = T))[2])
x <- unlist(strsplit(x, split = 'p', fixed = T))[1]
x <- substring(gsub("[.]","",x),1,Dec)
y <- c()
for(i in 1:Dec){
    y[i] <- as.integer(substring(x,i,i))
}

y

Thanks again for the help!