Re: [R] binary numbers

About this list Date view Thread view Subject view Author view Attachment view

From: Martin Maechler (maechler@stat.math.ethz.ch)
Date: Thu 15 Apr 2004 - 22:55:09 EST


Message-id: <16510.34349.928143.242715@gargle.gargle.HOWL>


>>>>> "Samuel" == Samuel Edward Kemp <sam.kemp2@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.

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html


About this list Date view Thread view Subject view Author view Attachment view

This archive was generated by hypermail 2.1.3 : Mon 03 May 2004 - 18:41:20 EST