4

How do I convert 64-bit hexadecimal strings in R?

> library(int64)
> as.int64("7f2d36a2a000")
[1] NA
Warning message:
In as.int64("7f2d36a2a000") : NAs introduced
> as.int64("0x7f2d36a2a000")
[1] NA
Warning message:
In as.int64("0x7f2d36a2a000") : NAs introduced
smci
  • 32,567
  • 20
  • 113
  • 146
kgibm
  • 852
  • 10
  • 22
  • 2
    That's an orphaned package that has been removed from CRAN. Consider bit64: http://cran.r-project.org/web/packages/bit64/index.html or Rmpfr: http://cran.r-project.org/web/packages/Rmpfr/index.html – IRTFM Oct 10 '14 at 15:36

2 Answers2

8

For a number that large, you'll need to load a package that supports representations of arbitrarily large numbers. Rmpfr is one example:

library(Rmpfr)

## Check that it works as expected on smaller numbers:
strtoi("ff", base=16)
# [1] 255
mpfr("ff", base=16)
# 1 'mpfr' number of precision  8   bits 
# [1] 255
as.integer(mpfr("ff", base=16)
# [1] 255

## Then apply it with (more) confidence to larger numbers: 
mpfr("7f2d36a2a000", base=16)
# 1 'mpfr' number of precision  48   bits 
# [1] 139832166883328
mpfr("7f2d36a2a0007f2d36a2a0007f2d36a2a0007f2d36a2a000", base=16)
# 1 'mpfr' number of precision  192   bits 
# [1] 3118361524223520784583964884878580812558070356334996529152
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
7

Here's a way using bit64.

library(bit64)
str <- "7f2d36a2a000"
as.integer64(as.numeric(paste0("0x",str)))
# integer64
[1] 139832166883328
jlhoward
  • 58,004
  • 7
  • 97
  • 140
  • 4
    Careful with this. `as.numeric` is double precision and has only 53 precision bits. So it might introduce rounding errors in the last digits! – Davor Josipovic Dec 11 '19 at 18:51