[R] convert to binary to decimal

Marc Schwartz marc_schwartz at comcast.net
Thu Feb 15 17:10:21 CET 2007


On Thu, 2007-02-15 at 16:38 +0100, Martin Feldkircher wrote:
> Hello,
> we need to convert a logical vector to a (decimal) integer. Example:
> 
> a=c(TRUE, FALSE, TRUE) (binary number 101)
> 
> the function we are looking for should return
> 
> dec2bin(a)=5
> 
> Is there a package for such a function or is it even implemented in the 
> base package? We found the hexmode and octmode command, but not a 
> binmode. We know how to program it ourselves however we are looking for 
> a computationally efficient algorithm.
> 
> Martin and Stefan

This is a modification of a function that I had posted a while back, so
that it handles 'x' as a logical vector. I added the first line in the
function to convert the logical vector to it's numeric equivalent and
then coerce to character:

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


a <- c(TRUE, FALSE, TRUE)

> bin2dec(a)
[1] 5

HTH,

Marc Schwartz



More information about the R-help mailing list