[R] Conversion to Binary (base2)

Erich Neuwirth erich.neuwirth at univie.ac.at
Fri Sep 26 00:55:36 CEST 2008


Since I have to teach number base conversion within 2 weeks,
I could not resist:

numberInBase <-  function(number,base){
  numberInBaseRecur<-function(number,base){
    lastDigit<-function(number,base) number %% base
    if (number == 0) result <- c(0)
    else result <- c(numberInBaseRecur(number %/% base,base),
                     lastDigit(number,base))
    result
  }
  result <- numberInBaseRecur(number,base)
  while (result[1]== 0 && length(result)>1) result <- result[-1]
  result
}

makeDigitSeq <- function(digiseq){
  digits <- c(as.character(0:9),LETTERS)
  paste(sapply(digiseq,function(x)digits[x+1]),collapse="")
}


makeDigitSeq(numberInBase(21,2))
probably does what you want.

This works up to base 36.




Jason Thibodeau wrote:
> Hello,
> 
> Is there a simple way to take an input, and convert the decimal integers to
> binary? In this case, I have a CSV file, and I need to convert the first
> column of every line to binary.
> 
> Thanks.
> 
> 
> 
> ------------------------------------------------------------------------
> 
> 
> No virus found in this incoming message.
> Checked by AVG - http://www.avg.com 
> Version: 8.0.169 / Virus Database: 270.7.2/1689 - Release Date: 9/24/2008 6:51 PM
> 

-- 
Erich Neuwirth, University of Vienna
Faculty of Computer Science
Computer Supported Didactics Working Group
Visit our SunSITE at http://sunsite.univie.ac.at
Phone: +43-1-4277-39464 Fax: +43-1-4277-39459



More information about the R-help mailing list