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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With