[R] Convert decimal to binary data

Spencer Graves spencer.graves at pdf.com
Mon Sep 15 02:27:38 CEST 2003


	  www.r-project.org -> search -> "R site search" for "conver to binary" 
reveals a function "ra2ba" in library bindata.  Have you considered this?

	  If your "decimal" is an integer, then the following might serve:

integer.base.b <-
function(x, b=2){
	xi <- as.integer(x)
	if(any(is.na(xi) | ((x-xi)!=0)))
		print(list(ERROR="x not integer", x=x))
	N <- length(x)
	xMax <- max(x)	
	ndigits <- (floor(logb(xMax, base=2))+1)
	Base.b <- array(NA, dim=c(N, ndigits))
	for(i in 1:ndigits){#i <- 1
		Base.b[, ndigits-i+1] <- (x %% b)
		x <- (x %/% b)
	}
	if(N ==1) Base.b[1, ] else Base.b
}

 > integer.base.b(x=1:9)
       [,1] [,2] [,3] [,4]
  [1,]    0    0    0    1
  [2,]    0    0    1    0
  [3,]    0    0    1    1
  [4,]    0    1    0    0
  [5,]    0    1    0    1
  [6,]    0    1    1    0
  [7,]    0    1    1    1
  [8,]    1    0    0    0
  [9,]    1    0    0    1
 > integer.base.b(123)
[1] 1 1 1 1 0 1 1

(in S-Plus 6.1 and R 1.7.1).
hope this helps.
spencer graves

Paul Delmar wrote:
> Hi,
>  
> I would like to convert a decimal into a binary number, for instance :
> 2->(1,0)
>  
> Any one knows how to do that ?
>  
> Thanks a lot 
>  
> paul
> 
> ---
> 
> 
> 
>  
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help




More information about the R-help mailing list