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:Bert Gunter (gunt@gene.com)
Date:Feb 15, 2007 8:52:54 am
List:org.r-project.r-help

why not simply:

sum(x * 2^(rev(seq_along(x)) - 1)) ?

-----Original Message----- From: r-he@stat.math.ethz.ch [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Roland Rau Sent: Thursday, February 15, 2007 8:22 AM To: marc_schwartz at comcast.net Cc: r-help at stat.math.ethz.ch Subject: Re: [R] convert to binary to decimal

That was a nice quick distraction. Unfortunately, I am not the first to answer. :-( Anyway, I offer two solutions (which are different from the one of Marc Schwartz); I wrote it quickly but I hope they are correct.

Enjoy and thanks, Roland

a <- c(TRUE, FALSE, TRUE) b <- c(TRUE, FALSE, TRUE, TRUE)

bin2dec.easy <- function(binaryvector) { sum(2^(which(rev(binaryvector)==TRUE)-1)) }

bin2dec.recursive <- function(binaryvector) { reversed.input <- rev(binaryvector) binaryhelper(reversed.input, 0, 0) }

binaryhelper <- function(binvector, currentpower, currentresult) { if (length(binvector)<1) { currentresult } else { if (binvector[1]) { binaryhelper(binvector[-1], currentpower+1, currentresult+2^currentpower) } else { binaryhelper(binvector[-1], currentpower+1, currentresult) } } }

bin2dec.easy(a) bin2dec.recursive(a) bin2dec.easy(b) bin2dec.recursive(b)

On 2/15/07, Marc Schwartz <marc_schwartz at comcast.net> wrote:

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,

[[alternative HTML version deleted]]