【问题标题】:How do I convert 64-bit hexadecimal strings in R?如何在 R 中转换 64 位十六进制字符串?
【发布时间】:2014-12-05 19:36:48
【问题描述】:

如何在 R 中转换 64 位十六进制字符串?

> 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

【问题讨论】:

标签: r type-conversion int64


【解决方案1】:

对于这么大的数字,您需要加载一个支持任意大数字表示的包。 Rmpfr 就是一个例子:

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

【讨论】:

    【解决方案2】:

    这是一种使用bit64的方法。

    library(bit64)
    str <- "7f2d36a2a000"
    as.integer64(as.numeric(paste0("0x",str)))
    # integer64
    [1] 139832166883328
    

    【讨论】:

    • 小心这个。 as.numeric 是双精度的,只有 53 个精度位。所以它可能会在最后一位数字中引入舍入错误!
    猜你喜欢
    • 1970-01-01
    • 2013-02-07
    • 2021-01-10
    • 2019-07-27
    • 2021-09-30
    • 1970-01-01
    • 2017-08-23
    • 2014-03-19
    相关资源
    最近更新 更多