10 messages in org.r-project.r-help[R] convert to binary to decimal
FromSent OnAttachments
Martin FeldkircherFeb 15, 2007 7:37 am 
Marc SchwartzFeb 15, 2007 8:09 am 
Roland RauFeb 15, 2007 8:21 am 
Bert GunterFeb 15, 2007 8:52 am 
Roland RauFeb 15, 2007 9:13 am 
Marc SchwartzFeb 15, 2007 9:21 am 
Petr PikalFeb 15, 2007 11:19 pm 
Roland RauFeb 16, 2007 7:52 am 
Jim RegetzFeb 16, 2007 5:44 pm 
Henrik BengtssonFeb 17, 2007 5:14 pm 
Actions with this message:
Paste this link in email or IM:
Paste this link in email or IM:
Atom feed for this thread
Paste this URL into your reader:
Subject:[R] convert to binary to decimalActions...
From:Marc Schwartz (marc@comcast.net)
Date:Feb 15, 2007 8:09:58 am
List:org.r-project.r-help

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,