[R] binary representation of an integer?

Thomas Lumley thomas at biostat.washington.edu
Tue Feb 15 20:42:58 CET 2000


On Tue, 15 Feb 2000, Mai Zhou wrote:

> Is there a function or other ways in R that can find the 
> binary representation of an integer?
> (or list all those representations for integers 0:63, for example)
> OR do I have to built such a table?
> 
> i.e.   something like  binary(3)= 11
>                        binary(4)= 100  etc.
> 

Here's a function that works for integers up to 2^10-1, so that the value
can be returned as an integer (if you have a 64bit machine you may be able
to use a larger value of 10)

binary<-function(i) {
a<-2^(0:9)
b<-2*a
sapply(i,function(x) sum(10^(0:9)[(x %% b)>=a]))
}


And this one works up to 2^32-1 but returns a string with leading zeros

binarys<-function(i) {
a<-2^(31:0)
b<-2*a
sapply(i,function(x) paste(as.integer((x %% b)>=a),collapse=""))
}

Either could be improved, but it's probably not worth much effort.

	-thomas

Thomas Lumley
Assistant Professor, Biostatistics
University of Washington, Seattle

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list