strtoi cannot convert string to integer, returns NA

32-bit binary integer string conversion fails. See below

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

Any ideas what could be the problem?

+5
source share
1 answer

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

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

The maximum integer that my machine (and probably yours) can process for an integer:

 .Machine$integer.max # [1] 2147483647 

Note that the documentation warns of overflow (from ?strtoi ):

Values ​​that cannot be interpreted as integers or overflows are returned as NA_integer_ .

What you can do is write your own function, which returns the output as a number 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 
+9
source

Source: https://habr.com/ru/post/1448035/


All Articles