[R] as.integer with base other than ten.

Marc Schwartz (via MN) mschwartz at mn.rr.com
Mon Nov 14 20:30:29 CET 2005


On Mon, 2005-11-14 at 19:01 +0000, William Astle wrote:
> Is there an R function analogous to the C function strtol? 
> I would like to convert a binary string into an integer.
> 
> Cheers for advice
> 
> Will


There was some discussion in the past and you might want to search the
archive for a more generic solution for any base to any base, but for
binary to decimal specifically, something like the following will work:

bin2dec <- function(x)
{
  b <- as.numeric(unlist(strsplit(x, "")))
  pow <- 2 ^ ((length(b) - 1):0)
  sum(pow[b == 1])
}


The function takes the binary string and splits it up into individual
numbers ('b'). It then creates a vector of powers of 2 as long as 'b'
less one through 0 ('pow').  It then takes the sum of the values of pow,
indexed by 'b == 1'.


> bin2dec("101")
[1] 5

> bin2dec("1111")
[1] 15

> bin2dec("1011111")
[1] 95


HTH,

Marc Schwartz




More information about the R-help mailing list