从字符串到整数的 32 位二进制字符串转换失败。见下文
strtoi("10101101100110001110011001111111", base=2)
# [1] NA
任何想法可能是什么问题?
最佳答案
它看起来像 strtoi
无法处理大于 2^31
的数字:
strtoi("1111111111111111111111111111111", base=2L)
# [1] 2147483647
strtoi("10000000000000000000000000000000", base=2L)
# [1] NA
这是我的机器(也可能是你的)可以处理的最大整数:
.Machine$integer.max
# [1] 2147483647
请注意,文档确实警告溢出(来自
?strtoi
):Values which cannot be interpreted as integers or would overflow are returned as
NA_integer_
.
您可以做的是编写自己的函数,将输出作为数字而不是整数返回:
convert <- function(x) {
y <- as.numeric(strsplit(x, "")[[1]])
sum(y * 2^rev((seq_along(y)-1)))
}
convert("1111111111111111111111111111111")
# [1] 2147483647
convert("10000000000000000000000000000000")
# [1] 2147483648
关于r - strtoi 无法将字符串转换为整数,返回 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13536832/