2

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
user20650
  • 24,654
  • 5
  • 56
  • 91
  • 1
    I think one issue is that R can't represent the integer `13256712356712312361` (look at `print(x, digits=22)`). There might be something in `Rmpfr` which can help (it does have a `formatBin` function) – user20650 Jan 31 '21 at 16:02
  • @user20650 Thank you for the suggestion! I was able to get something to work using formatBin in Rmpfr. – Jared Scripture Jan 31 '21 at 20:08
  • 1
    great stuff; it would be good if you could add an aswer – user20650 Jan 31 '21 at 20:09

1 Answers1

1

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!