Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strtoi fails to convert string to integer, returns NA

Tags:

r

32-bit binary string conversion from string to integer fails. See below

strtoi("10101101100110001110011001111111", base=2)
# [1] NA

Any ideas what the problem might be ?

like image 596
okaytee Avatar asked Nov 23 '12 23:11

okaytee


1 Answers

It looks like strtoi cannot handle numbers greater than 2^31:

strtoi("1111111111111111111111111111111", base=2L)
# [1] 2147483647
strtoi("10000000000000000000000000000000", base=2L)
# [1] NA

which is the maximum integer my machine (and probably yours) can handle for an integer:

.Machine$integer.max
# [1] 2147483647

Note that the documentation does warn about overflow (from ?strtoi):

Values which cannot be interpreted as integers or would overflow are returned as NA_integer_.

What you can do is write your own function that returns the output as a numeric instead of an 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
like image 77
flodel Avatar answered Oct 07 '22 23:10

flodel