gpt4 book ai didi

r - strtoi 无法将字符串转换为整数,返回 NA

转载 作者:行者123 更新时间:2023-12-04 12:33:36 24 4
gpt4 key购买 nike

从字符串到整数的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com