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.
Thanks.
Mai Zhou
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
binary representation of an integer?
3 messages · Mai Zhou, Thomas Lumley, Peter Dalgaard
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
Thomas Lumley <thomas at biostat.washington.edu> writes:
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.
And there's also: bb<-function(i) if (i) paste(bb(i %/% 2), i %% 2, sep="") else "" which works for all integer 0 < i < 2^54 on IEEE machines.
O__ ---- Peter Dalgaard Blegdamsvej 3 c/ /'_ --- Dept. of Biostatistics 2200 Cph. N (*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918 ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907 -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.- 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 _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._