8

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 ?

1 Answer 1

12

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.