[R] binary numbers

Martin Maechler maechler at stat.math.ethz.ch
Thu Apr 15 14:55:09 CEST 2004


>>>>> "Samuel" == Samuel Edward Kemp <sam.kemp2 at ntlworld.com>
>>>>>     on Wed, 14 Apr 2004 22:20:24 +0100 writes:

    Samuel> Hi, Is there a function in R that lets one represent
    Samuel> an integer in binary format for a given number of
    Samuel> bits? So an example would be....

    >> binary.function(num=5, num.of.bits=8) "00000101"

    Samuel> Or, is this something I have to write myself?

no.  In package "sfsmisc", there's also

>>   digitsBase              package:sfsmisc              R Documentation
>> 
>>   Digit/Bit Representation of Integers in any Base
>> 
>>   Description:
>> 
>>        Compute the vector of "digits" A of the 'base' b representation of
>>        a number N, N = sum(k = 0:M ; A[M-k] * b^k).
>> 
>>   Usage:
>> 
>>        digitsBase(x, base = 2, ndigits = 1 + floor(log(max(x), base)))

e.g.,

> library(sfsmisc) # after installing it

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

> empty.dimnames(digitsBase(0:33, 2)) # binary
                                                                    
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0
 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0
 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 0
 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0
 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

where you see that it does work vectorized.




More information about the R-help mailing list