[R] Conversion to Binary (base2)

Martin Maechler maechler at stat.math.ethz.ch
Fri Sep 26 09:55:56 CEST 2008


>>>>> "EN" == Erich Neuwirth <erich.neuwirth at univie.ac.at>
>>>>>     on Fri, 26 Sep 2008 00:55:36 +0200 writes:

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

Brian Ripley mentioned the functionality in package 'sfsmisc'
and this part {base conversion for integers} goes back to S-plus
code I wrote in 1991.
It works with a simple S3 class  "baseInt"
is vectorized and fast without a need to compiled code,
in spirit very similar to Erich's proposals below,
but a bit more elegant (no loops) and probably a bit more flexible.

E.g.

> digitsBase(0:10)
Class 'basedInt'(base = 2) [1:11]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
[1,]    0    0    0    0    0    0    0    0    1     1     1
[2,]    0    0    0    0    1    1    1    1    0     0     0
[3,]    0    0    1    1    0    0    1    1    0     0     1
[4,]    0    1    0    1    0    1    0    1    0     1     0

But really look at the examples  in  help(digitsBase) 
for more.

Martin Maechler, ETH Zurich

>> 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.


p

  >> 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.

>> -- 
>> 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